Get a list of all second order keys in a nested dictionary

From my dictionary of dictionaries, I would like to get 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. it years

is ['1998', '2000', '1999']

), but I'm sure there must be a better / shorter way to get a list of all the keys of nested dictionaries.

+3


source to share


2 answers


You can use a clear assignment:

>>>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 set

to a list.

>>> list(s)
['1999', '1998', '2000']

      

+6


source


>>> 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 rather @Kasra's answer :)

0


source







All Articles