[英]How to simplify a dictionary of nested lists in python?
我目前有這本帶有嵌套列表的字典:
dict_with_nested_list = {
'B': [['a', 2], ['b', 4]],
'A': [['a', 1], ['b', 3]]
}
correct_order = ['A', 'B']
我正在嘗試簡化它,以便每個嵌套列表的順序正確,並且其元素是鍵及其對應的值:
desired_output = [
['a', 1, 2],
['b', 3, 4]
]
我強烈建議保留某種字典結構,並為每個值list
一個list
。 如果需要,可以稍后將其轉換為其他結構。
>>> import collections
>>> dict_with_nested_list = {
... 'B': [['a', 2], ['b', 4]],
... 'A': [['a', 1], ['b', 3]]
... }
>>> result = collections.defaultdict(list)
>>> for l in dict_with_nested_list.values():
... for k,v in l:
... result[k].append(v)
...
>>> result = {k:sorted(v) for k,v in result.items()}
>>> result
{'b': [3, 4], 'a': [1, 2]}
>>> sorted(result.items())
[('a', [1, 2]), ('b', [3, 4])]
>>> [[k]+v for k,v in sorted(result.items())]
[['a', 1, 2], ['b', 3, 4]]
from collections import OrderedDict
ret = OrderedDict()
for order in correct_order:
for key, value in dict_with_nested_list[order]:
if key not in ret:
ret[key] = []
ret[key].append(value)
print [[key] + value for key, value in ret.items()]
您可以將其變成這樣的合理詞典
from collections import defaultdict
dict_output = defaultdict(list)
for key, list_of_pairs in sorted(dict_with_nested_list.items()):
for lowerkey, value in list_of_pairs:
dict_output[lowerkey].append(value)
print(dict(dict_output))
這導致該命令:
{'a': [1, 2], 'b': [3, 4]}
您可以像這樣將字典轉換為所需的輸出:
desired_output = [[key] + values for key, values in sorted(dict_output.items())]
print(desired_output)
導致
[['a', 1, 2], ['b', 3, 4]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.