简体   繁体   中英

get all the unique secondary keys in a dictionary python

I have a 2d dictionary eg:

 d[a1][b1] = v1
 d[a1][b2] = v2
 d[a2][b1] = v3
 d[a2][b3] = v4

In the above examples the unique secondary keys are b1, b2, b3?

How do i return the list [b1,b2,b3] in python? Thanks

s = list(set(key2 for key1 in d for key2 in d[key1]))

Since the dict could be many dimensions, the way to go about getting a list of the values from the 2nd level is to just loop through the dict as normal.

My suggestion is for you to look into perhaps using something like itertools . Itertools can help make quick and fancy work of a use case like yours.

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