[英]Accessing list of dictionaries in python and sort it using value (Nested dictionary)
I have a list of 50 dictionaries and want to be sorted by a value of 'Key2' of that dictionary.我有一个包含 50 个字典的列表,并希望按该字典的“Key2”值进行排序。
list1= [{'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]} ,
{'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]}]
Key2 can statically be accessed by: Key2 可以通过以下方式静态访问:
>>>print list1[0]['outside_key1'][0]['key2']
xyz
Now sorting based on 'key2' Like:现在根据'key2'进行排序,例如:
sorted_list = sorted(list1, key=lambda k: k[???])
Final sorted by value becomes:最终按值排序变为:
[{'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]} ,
{'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]}]
So my questions:所以我的问题:
1. How can i dynamically access the value of 'Key2'? 1. 如何动态访问“Key2”的值?
2. How can i sort list of dictionary based on the value of 'Key2'? 2. 如何根据“Key2”的值对字典列表进行排序?
list1= [{'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]} ,
{'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]}]
sort_on = "key2"
decorated = [(dict_.values()[0][0][sort_on], dict_) for dict_ in list1]
decorated.sort()
result = [dict_ for (key, dict_) in decorated]
print result
dict_.values()
get the outside dic values, the first [0] get the value of outside_key1
, the second [0] get the first value of inner list. dict_.values()
获取外部 dic 值,第一个 [0] 获取outside_key1
的值,第二个 [0] 获取内部列表的第一个值。
Here's the fastest way to do it, as it avoids using a custom comparison function, instead using builtin comparisons.
这是最快的方法,因为它避免使用自定义比较函数,而是使用内置比较。 You can get more information from Sorting Lists of Dictionaries
您可以从字典排序列表中获取更多信息
Assuming you have only a single key for each of the dictionaries, you could do something like:假设每个字典只有一个键,您可以执行以下操作:
sorted(list1, key=lambda d: d[next(iter(d))][0]['key2'])
Here: d[next(iter(d))]
will give the value of the first key associated with d
.这里:
d[next(iter(d))]
将给出与d
关联的第一个键的值。 Of course, dictionaries are unordered, so the "first" key only has meaning when you have only a single key-value pair in the dict...当然,字典是无序的,所以“第一个”键只有在字典中只有一个键值对时才有意义......
FWIW, it seems like your data-structure is really getting in the way of a clean solution here. FWIW,您的数据结构似乎真的妨碍了这里的干净解决方案。 It seems like a flat list of dict would be a better way to store the data:
似乎 dict 的平面列表是存储数据的更好方法:
list1 = [
{'key1': 'one', 'key2': 'abc', 'key3':'three'},
{ 'key1': 'one', 'key2': 'xyz','key3':'three'},
]
As having dicts with only one value and lists with only one value tend to make the container a bit overkill.因为只有一个值的字典和只有一个值的列表往往会使容器有点矫枉过正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.