简体   繁体   中英

single list comprehension to unpack nested dictionary

I'd like to turn this

a = {'a': {'b': 'b aw', 'c': 'c aw'}, 'b': {'b': 'b2 aw', 'c': 'c2 aw'}, 'c': {}}

into this

['b aw', 'c aw', 'b2 aw', 'c2 aw']

with a list comprehension. I think I need some way to make this expression 'legal':

a2 = [a1 for a1 in a.values().values()]

I don't want dict(a.values) because that will just get me back to my original dictionary, a. I know there are many ways to do this with a for loop, but is there a way to do this without a for loop? Thanks.

You need to loop over the values of the values of your dict :

>>> [i for j in a.values() for i in j.values()]
['c aw', 'b aw', 'c2 aw', 'b2 aw']

The way to make your original values expression

[a1 for a1 in a.values().values()]

legal, is like so:

import itertools

itertools.chain.from_iterable([v.values() for v in a.values()])

Explanation: the internal list is a list of lists - the values corresponding to each of the values. itertools.chain.from_iterable flattens it.

You can do this:

a = {'a': {'b': 'b aw', 'c': 'c aw'}, 'b': {'b': 'b2 aw', 'c': 'c2 aw'}, 'c': {}}    
a2 = [a1 for a1 in a.values()]
a3 = [a3.values() for a3 in a2]
a3.sort()

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