Let\'s say I have a list a
in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following o
You can also try this approach save the keys and values in different list and then use dict method
data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']
keys=[]
values=[]
for i,j in enumerate(data):
if i%2==0:
keys.append(j)
else:
values.append(j)
print(dict(zip(keys,values)))
output:
{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}
May not be the most pythonic, but
>>> b = {}
>>> for i in range(0, len(a), 2):
b[a[i]] = a[i+1]
You can also do it like this (string to list conversion here, then conversion to a dictionary)
string_list = """
Hello World
Goodbye Night
Great Day
Final Sunset
""".split()
string_list = dict(zip(string_list[::2],string_list[1::2]))
print string_list
You can use a dict comprehension for this pretty easily:
a = ['hello','world','1','2']
my_dict = {item : a[index+1] for index, item in enumerate(a) if index % 2 == 0}
This is equivalent to the for loop below:
my_dict = {}
for index, item in enumerate(a):
if index % 2 == 0:
my_dict[item] = a[index+1]
I am not sure if this is pythonic, but seems to work
def alternate_list(a):
return a[::2], a[1::2]
key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))
Something i find pretty cool, which is that if your list is only 2 items long:
ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}
Remember, dict accepts any iterable containing an iterable where each item in the iterable must itself be an iterable with exactly two objects.