简体   繁体   中英

List + Dictionary comprehension key filter

With the following example schema:

test_dict = {
    '2015': {
        'bar1': [1, 2, 3, 4],
        'bar2': [2, 2, 2, 2],
        'bar3': [4, 3, 2, 1]
    },
    '2016': {
        'bar1': [1, 2, 3, 4],
        'bar2': [5, 5, 5, 5],
        'bar3': [4, 3, 2, 1]
    },
    '2017': {
        'bar1': [1, 2, 3, 4],
        'bar2': [4, 4, 4, 4],
        'bar3': [4, 3, 2, 1]
    }
}

I need to gather all the lists specified by the 2nd dict key. So I currently have the code:

await asyncio.gather(*[get_matches(browser, ser) for ser in test_dict['2015']['bar2']])

but I want to gather all the lists that belong to each bar2 key meaning I want to comprehend into gather() : `

test_dict['2015']['bar2']
test_dict['2016']['bar2']
test_dict['2017']['bar2']

by specifying bar2 so that gather() will receive:

[2, 2, 2, 2], [5, 5, 5, 5], [4, 4, 4, 4]

how can I?

I tried doing it like this but didn't work:

{k2:v2 for k2,v2 in {k:v for k,v in test.items()}.items() if k2 == 'bar2' }

not to mention gather will want a dict in the end.

If you need

get_matches(browser, [2, 2, 2, 2]), get_matches(browser, [5, 5, 5, 5]), ...

then

[ get_matches(browser, v['bar2']) for k, v in test_dict.items() ]

If you need

get_matches(browser, 2), get_matches(browser, 2), ...

then

[ get_matches(browser, ser) for k, v in test_dict.items() for ser in v['bar2'] ]

If you need only list

[[2, 2, 2, 2], [5, 5, 5, 5], [4, 4, 4, 4]]

then

[ v['bar2'] for k, v in test_dict.items() ]

or even

[ v['bar2'] for v in test_dict.values() ]

Minimal working code

test_dict = {
    '2015': {
        'bar1': [1, 2, 3, 4],
        'bar2': [2, 2, 2, 2],
        'bar3': [4, 3, 2, 1]
    },
    '2016': {
        'bar1': [1, 2, 3, 4],
        'bar2': [5, 5, 5, 5],
        'bar3': [4, 3, 2, 1]
    },
    '2017': {
        'bar1': [1, 2, 3, 4],
        'bar2': [4, 4, 4, 4],
        'bar3': [4, 3, 2, 1]
    }
}


print([('browser', v['bar2']) for k, v in test_dict.items()])
print('---')
print([('browser', ser) for k, v in test_dict.items() for ser in v['bar2']])
print('---')
print([ v['bar2'] for k, v in test_dict.items() ])
print([ v['bar2'] for v in test_dict.values() ])

Result:

[('browser', [2, 2, 2, 2]), ('browser', [5, 5, 5, 5]), ('browser', [4, 4, 4, 4])]
---
[('browser', 2), ('browser', 2), ('browser', 2), ('browser', 2), ('browser', 5), ('browser', 5), ('browser', 5), ('browser', 5), ('browser', 4), ('browser', 4), ('browser', 4), ('browser', 4)]
---
[[2, 2, 2, 2], [5, 5, 5, 5], [4, 4, 4, 4]]
[[2, 2, 2, 2], [5, 5, 5, 5], [4, 4, 4, 4]]

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