获取嵌套字典中所有secondorder键的列表

2024-09-28 17:02:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从我的字典里收到所有二阶键的列表。在

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'}
}

我知道

^{pr2}$

其中uniqfy()来自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

一切都按预期工作(即years['1998', '2000', '1999']),但是我确信一定有更好/更短的方法来获取嵌套字典的所有键的列表。在


Tags: none列表newreturnif字典defresult
2条回答

你可以使用集合理解:

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

如果您只需要一个list对象,可以使用list()set转换为list。在

^{pr2}$
>>> 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']

编辑:我更喜欢@Kasra的回答:)

相关问题 更多 >