简体   繁体   中英

Creating tuple pairs from a dictionary that has a list as value

I am trying to get a list of tuple pairs from a dictionary that has a list as value.

d={ 'a': [1,2], 'b': [4,5], 'c': [7,8] }
print(d.items())
>>[('a', [1, 2]), ('b', [4, 5]),('c', [7, 8]) ]

how do I get the list in this form

[('a', 1),('a', 2), ('b',4),('b',5),('c',7),('c',8)]

Using a simple list comprehension:

d = {'a': [1,2,3], 'b': [4,5,6]}
l = [(k, v) for k in d for v in d[k]]
print(l)  # => [('a', 1), ('a', 2), ('a', 3), ('b', 4), ('b', 5), ('b', 6)]

There's likely other ways to do it, but this is simplistic and doesn't require other libraries.

Its Simple, use one-liner :)

>>>
>>> d={ 'a': [1,2], 'b': [4,5], 'c': [7,8] }
>>> [(key,item) for item in value for  key, value in d.iteritems()]
[('a', 4), ('c', 4), ('b', 4), ('a', 5), ('c', 5), ('b', 5)]
>>>

if you want to sort use built in funciton

>>> d={ 'a': [1,2], 'b': [4,5], 'c': [7,8] }
>>> sorted([(key,item) for item in value for  key, value in d.iteritems()])
[('a', 4), ('a', 5), ('b', 4), ('b', 5), ('c', 4), ('c', 5)]
>>>
>>> d = {'a': [1, 2], 'b': [4, 5], 'c': [7, 8]}

You can access the key, value pairs using dict.items() .

>>> list(d.items())
[('a', [1, 2]), ('c', [7, 8]), ('b', [4, 5])]

Then you can iterate over the pairs and iterate over the list values:

>>> [(key, value) for (key, values) in d.items()
...  for value in values]
[('a', 1), ('a', 2), ('c', 7), ('c', 8), ('b', 4), ('b', 5)]

The dictionary keys are not ordered alphabetically. If you want the exact output in your question you need to sort them, either before creating your list or after:

>>> pairs = _
>>> sorted(pairs)
[('a', 1), ('a', 2), ('b', 4), ('b', 5), ('c', 7), ('c', 8)]

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