-
Notifications
You must be signed in to change notification settings - Fork 0
Dictionary zip() & Comprehension
KeithChamberlain edited this page Apr 25, 2021
·
1 revision
An elegant example of how to use zip() and a dictionary comprehension on LI by Thom Ives.
Quickly define a dict()ionary based on two list() objects using zip(), then reverse the keys and values in a new dictionary using a dictionary comprehension.
num_names = ['one', 'two', 'three', 'four', 'five']
nums = [1, 2, 3, 4, 5]
names_nums_D = dict(zip(num_names, nums))
nums_names_D = {v: k for k, v in names_nums_D.items()}
print(names_nums_D, '\n')
print(nums_names_D){'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}