How to unfold a python dictionary with lists as values into a list of key-value tuples with two elements? -


i have kind of dictionary:

{'a': [1, 2], 'b': [4, 5, 6]} 

i'd know how unfold list of tuples so:

[('a', 1), ('a', 2), ('b', 4), ('b', 5), ('b', 6)] 

what best way achieve in python 3?

simply use list comprehension:

[(k,vi) k,v in d.items() vi in v] 

with sample input, generates:

>>> d = {'a': [1, 2], 'b': [4, 5, 6]} >>> [(k,vi) k,v in d.items() vi in v] [('a', 1), ('a', 2), ('b', 4), ('b', 5), ('b', 6)] 

note in python versions (not recent one), dictionaries unordered. therefore order of keys can differ in output (not values per key). [('b', 4), ('b', 5), ('b', 6), ('a', 1), ('a', 2)] possible result well. cannot solve problem (with unfolding) since moment construct such dictionary, order lost.


Comments

Post a Comment

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -