开发者

Python: The best way to get complex dictionary values

开发者 https://www.devze.com 2023-02-16 12:39 出处:网络
I\'ve a dictionary in following format {\'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\'

I've a dictionary in following format

{'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-str开发者_StackOverflow社区ing': 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}]]}

what is the most effective way to get values of [15.0,12.0,12.0,12.0,45.0,,,,etc]


This is making all kinds of assumptions about the data you're dealing with, but in the example you give you could do this:

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

... where d is your dictionary as above. That evaluates to:

[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]


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


If you have a dictionary d, you can use d.values() to get all the values in the dictionary. For example:

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

精彩评论

暂无评论...
验证码 换一张
取 消