0

I have a list, and I'd like to convert it into a list of dictionaries in Python.

My list is:

a = ["a", "b", "c", "d", "e", "f"]

I'd like to convert it something like this:

[
    {'Key': 'a', 'Value': 'b'},
    {'Key': 'c', 'Value': 'd'},
    {'Key': 'e', 'Value': 'f'}
]
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Manzoor
  • 85
  • 1
  • 3
  • 10
  • You have 2 keys in each dictionary, 1 named `'Key'` and 1 named `'Value'`, this naming is confusing at best. Also when you ask a question like this, it's good to show what you've attempted. – Chris_Rands Nov 21 '16 at 09:52

3 Answers3

6

zip and a list comprehension are the way to go:

>>> a = ["a","b","c","d","e","f"]
>>> [{'key': k, 'value': v} for k, v in zip(a[::2], a[1::2])]
[{'value': 'b', 'key': 'a'}, {'value': 'd', 'key': 'c'}, {'value': 'f', 'key': 'e'}]

Notice how the list is sliced with a step of two starting at 0 and 1 and then zipped.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
3

Better way will be to use itertool.izip_longest() with list comprehension as it will place value as None in case elements are odd in number. For example:

>>> from itertools import izip_longest
>>> odd_list = ["a", "b", "c"]
>>> [{'key': k, 'value': v} for k, v in izip_longest(odd_list[::2], odd_list[1::2])]
[{'value': 'b', 'key': 'a'}, {'value': None, 'key': 'c'}]
#                                       ^ Value as None

However if it is safe to assume even count of elements, you may use zip() as well as:

>>> my_list = ["a","b","c","d","e","f"]
>>> [{'key': k, 'value': v} for k, v in zip(my_list[::2], my_list[1::2])]
[{'value': 'b', 'key': 'a'}, {'value': 'd', 'key': 'c'}, {'value': 'f', 'key': 'e'}]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

This can be one way of doing it:

lst = [{"Key": a[2 * i], "Value": a[2 * i + 1]} for i in range(len(a) / 2)]

Note: list a must have even number or elements in order to work

Fejs
  • 2,734
  • 3
  • 21
  • 40