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