Python Dictionary Comprehensions Made Simple
So, you are getting good at Python dictionaries, but you must keep stepping up the ladder.
Published in
3 min readJun 13, 2021
Copying each key and value to another dictionary
Traditional way:
a = {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
b = {}
for k, v in a.items():
b[k] = v
print(b)
>>> {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
Using Dictionary Comprehensions:
a = {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
b = {k: v for k, v in a.items()}
print(b)
>>> {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
Copying each key and value to another dictionary if a certain condition is met
Traditional way:
a = {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
b = {}
for k, v in a.items():
if v > 1:
b[k] = v
print(b)
>>> {'ho': 2, "let's": 3, 'go': 4}
Using Dictionary Comprehensions:
a = {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}b = {k: v for k, v in a.items() if v > 1}
print(b)
>>> {'ho': 2, "let's": 3, 'go': 4}
Converting two lists to one Dictionary
Traditional way:
a = ['hey', 'ho', "let's", "go"]
b = [1, 2, 3, 4]
c = {}
for item in a:
c[item] = b[a.index(item)]
print(c)
>>> {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
Using Dictionary Comprehensions:
a = ['hey', 'ho', "let's", "go"]
b = [1, 2, 3, 4]
c = {k: v for k, v in zip(a, b)}
print(c)
>>> {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
Using dict and zip (even simpler):
a = ['hey', 'ho', "let's", "go"]
b = [1, 2, 3, 4]
c = dict(zip(a, b))
print(c)
>>> {'hey': 1, 'ho': 2, "let's": 3, 'go': 4}
Finally, converting 3 lists to 1 dictionary with the last 2 lists as 1 value
Traditional way:
a = ['hey', 'ho', "let's", "go"]
b = [1, 2, 3, 4]
c = ['a', 'b', 'c', 'd']
d = {}
for item in a:
d[item] = [b[a.index(item)], c[a.index(item)]]
print(d)
>>> {'hey': [1, 'a'], 'ho': [2, 'b'], "let's": [3, 'c'], 'go': [4, 'd']}
Using Dictionary Comprehension with zip:
a = ['hey', 'ho', "let's", "go"]
b = [1, 2, 3, 4]
c = ['a', 'b', 'c', 'd']
e = { k: list(v) for k, v in zip(a, zip(b, c)) }
print(e)
>>> {'hey': [1, 'a'], 'ho': [2, 'b'], "let's": [3, 'c'], 'go': [4, 'd']}
Using dict, zip and map (much simpler):
a = ['hey', 'ho', "let's", "go"]
b = [1, 2, 3, 4]
c = ['a', 'b', 'c', 'd']
d = dict(zip(a, map(list, zip(b, c))))
print(d)
>>> {'hey': [1, 'a'], 'ho': [2, 'b'], "let's": [3, 'c'], 'go': [4, 'd']}
Conclusion
I hope you learned something new today, by learning this article.
Have you ever used any of these? Please let me know in the comments. You can also follow me here, so you can track what’s next to come.
More content at plainenglish.io