Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e. 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.

like image 379
MERose Avatar asked Mar 17 '23 08:03

MERose


1 Answers

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']
like image 145
Mazdak Avatar answered Apr 01 '23 01:04

Mazdak