Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Zip dict with keys [duplicate]

Tags:

python

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)]
like image 644
atp Avatar asked Mar 06 '11 01:03

atp


People also ask

Does ZIP remove duplicates Python?

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.

Can Python dictionary have duplicate keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

How do you get rid of duplicate keys 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.

Does dictionary accept duplicate keys?

[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<> .


2 Answers

map(dict, map(lambda t:zip(('num','char'),t), zip(list_nums,list_chars)))

gives:

[{'char': 'a', 'num': 1}, {'char': 'd', 'num': 18}]
like image 176
PaulMcG Avatar answered Oct 04 '22 00:10

PaulMcG


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.

like image 25
Sven Marnach Avatar answered Oct 04 '22 00:10

Sven Marnach