Python:获取复杂字典值的最佳方法

时间:2011-03-14 11:06:37

标签: python dictionary

我有以下格式的字典

  

{'array':[[{u'unsigned':15.0}],[{u'octet-string':12.0}],[{u'octet-string':12.0}],[{u' octet-string':12.0}],[{u'octet-string':45.0}],[{u'octet-string':78.0}],[{u'octet-string':89.0}],[{ u'octet-string':65.0}],[{u'octet-string':352.0}],[{u'octet-string':45.0}],[{u'octet-string':12.0}], [{u'octet-string':45.0}],[{u'octet-string':78.0}],[{u'octet-string':98.0}],[{u'octet-string':352.0} ],[{u'octet-string':56.0}],[{u'octet-string':89.0}],[{u'octet-string':78.0}],[{u'octet-string': 45.0}],[{u'octet-string':12.0}],[{u'octet-string':23.0}],[{u'octet-string':65.0}],[{u'octet-string ':65.0}],[{u'octet-string':45.0}],[{u'octet-string':78.0}],[{u'octet-string':899.0}],[{u'octet -string':8989.0}],[{u'octet-string':6565.0}],[{u'octet-string':323.0}],[{u'octet-string':1211.0}]]}

获取[15.0,12.0,12.0,12.0,45.0 ,,,, etc]等值的最有效方法是什么

3 个答案:

答案 0 :(得分:4)

这是对您正在处理的数据做出各种假设,但在您给出的示例中可以这样做:

[ a[0].values()[0] for a in d['array'] ]

...其中d是您上面的字典。评估结果为:

[15.0, 12.0, 12.0, 12.0, 45.0, 78.0, 89.0, 65.0, 352.0,
 45.0, 12.0, 45.0, 78.0, 98.0, 352.0, 56.0, 89.0, 78.0,
 45.0, 12.0, 23.0, 65.0, 65.0, 45.0, 78.0, 899.0, 8989.0,
 6565.0, 323.0, 1211.0]

答案 1 :(得分:0)

[elem[0].values()[0] for elem in yourDict['array']]

答案 2 :(得分:0)

如果您有字典d,则可以使用d.values()获取字典中的所有值。例如:

d = {'a': 1.0, 'b': 2.0}
print(d.values())   # [1.0, 2.0]