'Creating a dictionary from a list and fixed variable in Python
I am trying to create a dictionary from a list and a fixed variable. I know that zip() can create a dictionary from two lists but how can I adapt it to intake a fixed variable?
What works:
countries = ["Italy", "Germany", "Spain", "USA", "Switzerland"]
dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]
country_specialities = zip(countries, dishes)
What I need:
dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]
country = "uk"
To output:
menu = {"pizza": "uk", "sauerkraut": "uk", "paella": "uk", "Hamburger": "uk"}
Solution 1:[1]
{dish: country for dish in dishes}
Solution 2:[2]
You can use the dict.fromkeys() class method here:
dict.fromkeys(dishes, country)
Note that you should not use this where the default is a mutable value (unless you meant to share that mutable value among all the keys).
From the documentation:
Create a new dictionary with keys from seq and values set to value.
fromkeys()is a class method that returns a new dictionary. value defaults toNone.
This is going to be faster than using a dictionary comprehension; the looping over dishes is done entirely in C code, while a dict comprehension would execute the loop in Python bytecode instead.
If your list is going to contain 200.000 values, then that makes a huge difference:
>>> from timeit import timeit
>>> import random
>>> from string import ascii_lowercase
>>> values = [''.join([random.choice(ascii_lowercase) for _ in range(random.randint(20, 40))]) for _ in range(200000)]
>>> def dictcomp(values):
... return {v: 'default' for v in values}
...
>>> def dictfromkeys(values):
... return dict.fromkeys(values, 'default')
...
>>> timeit('f(values)', 'from __main__ import values, dictcomp as f', number=100)
4.984026908874512
>>> timeit('f(values)', 'from __main__ import values, dictfromkeys as f', number=100)
4.159089803695679
That's almost a second of difference between the two options when repeating the operation 100 times.
Solution 3:[3]
You can do this:
dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]
country = "uk"
menu = dict((dish, country) for dish in dishes)
Solution 4:[4]
Expanding on with what you were doing with zip
In [54]: dict(zip(dishes, [country] * len(dishes)) )
Out[54]: {'Hamburger': 'uk', 'paella': 'uk', 'pizza': 'uk', 'sauerkraut': 'uk'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Kugelman |
| Solution 2 | |
| Solution 3 | geckon |
| Solution 4 | fixxxer |
