這裏是我的解決方案:
import json
my_list = [['apple',{'john':3,'anna':4,'kitty':6}],['pear',{'john':4,'anna':3,'kitty':3}]]
name_list = [item[1] for item in my_list] # [{'john': 3, 'kitty': 6, 'anna': 4}, {'john': 4, 'kitty
names = name_list[0].keys() # ['john', 'kitty', 'anna']
name_values = [[item[key] for item in name_list] for key in names] # [[3, 4], [6, 3], [4, 3]]
result = {
'key': [item[0] for item in my_list],
'value': [
{'name': name, 'value': value}
for (name, value) in zip(names, name_values)
]
}
print(json.dumps(result, indent=4))
和輸出:
{
"value": [
{
"name": "john",
"value": [
3,
4
]
},
{
"name": "kitty",
"value": [
6,
3
]
},
{
"name": "anna",
"value": [
4,
3
]
}
],
"key": [
"apple",
"pear"
]
}
編輯:
emmm,只是找到了一個更好的方式來合併字典值。
如果name_dict象這樣:
>>> name_dict
[{'john': [3], 'kitty': [6], 'anna': [4]}, {'john': [4], 'kitty': [3], 'anna': [3]}]
任務會很容易。有什麼不同?該值是一個列表。
現在,我們可以用collections.Counter
來合併兩個詞典!
>>> Counter(name_dict[0]) + Counter(name_dict[1])
Counter({'kitty': [6, 3], 'anna': [4, 3], 'john': [3, 4]})
所以這裏是新的解決方案,我們首先將值轉換到一個列表:(跳過「密鑰」,只顯示「值」):
from collections import Counter
my_list = [['apple',{'john':3,'anna':4,'kitty':6}],['pear',{'john':4,'anna':3,'kitty':3}]]
name_list = [item[1] for item in my_list]
for item in name_list:
for key, value in item.items():
item[key] = [value]
name_values = dict(Counter(name_list[0]) + Counter(name_list[1])) # {'john': [3, 4], 'kitty': [6, 3], 'anna': [4, 3]}
print([{'name': name, 'value': value} for (name, value) in name_values.items()])
# output
[{'name': 'john', 'value': [3, 4]}, {'name': 'kitty', 'value': [6, 3]}, {'name': 'anna', 'value': [4, 3]}]
想分享你的企圖我們? – vaultah