简体   繁体   中英

getting a list of tuples out of dictionary keys and values

Say you have a dictionary of lists:

>>> a = {"a":[1, 3, 10, 2, 5], "b":[1, 0, 0, 1, 14]}
>>> a
{'a': [1, 3, 10, 2, 5], 'b': [1, 0, 0, 1, 14]}

From this dictionary, I would like to create another list, where each element is a (key, id) tuple, as follows:

>>> pairs = []
>>> for k,v in a.items():
...   for id in v:
...     pairs += [(k,id)]
... 
>>> print(pairs)
[('a', 1), ('a', 3), ('a', 10), ('a', 2), ('a', 5), ('b', 1), ('b', 0), ('b', 0), ('b', 1), ('b', 14)]

Is there a shortcut to do this? the previous code to create pairs is too verbose.

您可以使用双列表理解,但是这样可读性:

pairs = [(k, val) for k, l in a.items() for val in l]

This can also be done as:

>>> a = {"a":[1, 3, 10, 2, 5], "b":[1, 0, 0, 1, 14]}
>>> 
>>> [(k,v) for k in a for v in a[k]]
[('a', 1), ('a', 3), ('a', 10), ('a', 2), ('a', 5), ('b', 1), ('b', 0), ('b', 0), ('b', 1), ('b', 14)]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM