I have:
list_nums = [1,18]
list_chars = ['a','d']
I want:
list_num_chars = [{'num':1, 'char':'a'},
{'num':18, 'char':'d'}]
Is there a more elegant solution than:
list_num_chars = [{'num':a, 'char':b} for a,b in zip(list_nums, list_chars)]
Answer. If the list passed to the zip() function contains duplicate data, the duplicate created as part of the list comprehension will be treated as an update to the dictionary and change the value associated with the key. No error will be reported.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set. You must convert the dictionary or set back into a list to see a list whose duplicates have been removed.
[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
map(dict, map(lambda t:zip(('num','char'),t), zip(list_nums,list_chars)))
gives:
[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]
If the initial lists are very long, you might want to use itertools.izip()
instead of zip()
for slightly improved performance and less memory usage, but apart from this I can't think of a significantly "better" way to do it.
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