简体   繁体   中英

Get list of all second-order keys in nested dictionary

From my dictionary of dictionaries I would like to receive a list of all second-order keys.

myDict = {
    u'A': {'1998': u'ATLANTA'},
    u'B': {'1999': u'MANNHEIM'},
    u'C': {'2000': u'BERLIN'},
    u'D': {'1998': u'CHICAGO', '1999': u'PRINCETON'},
    u'E': {'2000': u'LOUISIANA'},
    u'F': {'1998': u'NEW YORK', '1999': u'NEW YORK'}
}

I do

years = []
for author in author_aff_dict:
    years.extend(author_aff_dict[author].keys())
print uniqfy(years)

where uniqfy() is from http://www.peterbe.com/plog/uniqifiers-benchmark :

def uniqfy(seq, idfun=None):
   if idfun is None:
       def idfun(x): return x
   seen = {}
   result = []
   for item in seq:
       marker = idfun(item)
       if marker in seen: continue
       seen[marker] = 1
       result.append(item)
   return result

Everything works as expected (ie years is ['1998', '2000', '1999'] ), but I am sure there must be a better/shorter way in getting a list of all keys of the nested dictionaries.

You can use a set comprehension :

>>>s= {j for i in myDict.values() for j in i}
set(['1999', '1998', '2000'])

Then if you just want a list object you can use list() to convert the set to list.

>>> list(s)
['1999', '1998', '2000']
>>> myList = []
>>> for i in myDict.values():
...     for j in i.keys():
...             if j not in myList: myList.append(j)
...             else: continue
... 
>>> myList
['1998', '2000', '1999']

edit: i'd prefer @Kasra's answer :)

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