To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
To convert a tuple to dictionary in Python, use the dict() method. A dictionary object can be constructed using a dict() function. The dict() function takes a tuple of tuples as an argument and returns the dictionary. Each tuple contains a key-value pair.
b = dict(zip(a[::2], a[1::2]))
If a
is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.
from itertools import izip
i = iter(a)
b = dict(izip(i, i))
In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range()
and len()
, which would normally be a code smell.
b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
So the iter()/izip()
method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip()
is already lazy in Python 3 so you don't need izip()
.
i = iter(a)
b = dict(zip(i, i))
In Python 3.8 and later you can write this on one line using the "walrus" operator (:=
):
b = dict(zip(i := iter(a), i))
Otherwise you'd need to use a semicolon to get it on one line.
Another option (courtesy of Alex Martelli - source):
dict(x[i:i+2] for i in range(0, len(x), 2))
If you have this:
a = ['bi','double','duo','two']
and you want this (each element of the list keying a given value (2 in this case)):
{'bi':2,'double':2,'duo':2,'two':2}
you can use:
>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}
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]
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.
May not be the most pythonic, but
>>> b = {}
>>> for i in range(0, len(a), 2):
b[a[i]] = a[i+1]
You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:
dict(izip(*([iter(a)]*2)))
If you have a generator a
, even better:
dict(izip(*([a]*2)))
Here's the rundown:
iter(h) #create an iterator from the array, no copies here
[]*2 #creates an array with two copies of the same iterator, the trick
izip(*()) #consumes the two iterators creating a tuple
dict() #puts the tuples into key,value of the dictionary
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With