我有幾個方案,以創建一個新的字典另一詞典:創建字典從以最快的和可擴展的方式
- 只有把這些字典與關鍵「總」名單不是零
- 刪除鍵詞典如「總」和「排名」
- 使用「姓名」鍵值爲鍵和「遊戲」的鍵值爲新字典
- 排序值的新字典 名單
值列表
我的代碼是:
# input dictionary
data =[
{'name': 'foo', 'rank': 3, 'game': 'football', 'total': 1},
{'name': 'bar', 'rank': 5, 'game': 'hockey', 'total': 0},
{'name': 'foo', 'rank': 7, 'game': 'tennis', 'total': 0},
{'name': 'foo', 'rank': 2, 'game': 'cricket', 'total': 2},
{'name': 'bar', 'rank': 1, 'game': 'cricket', 'total': 8},
]
result_list = []
merged_data = {}
result_data = {}
# Get the list of dict if key 'total' value is not zero
dict_without_total = [
den for den in data if den.get('total')
]
for my_dict in dict_without_total:
# deleting key 'brand' and 'total' from the
del my_dict['rank']
del my_dict['total']
result_data.update({
my_dict.get('name'): (my_dict.get('game'))
})
result_list.append(result_data)
# store all values of same keys in list and sort the values list
for result in result_list:
for keys, values in result.items():
if keys not in merged_data:
merged_data[keys] = []
merged_data[keys].append(values)
merged_data[keys].sort()
print merged_data
我的代碼輸出:
{
'bar': ['cricket', 'cricket', 'cricket'],
'foo': ['cricket', 'cricket', 'cricket']
}
預期結果:
{
'foo': ['cricket', 'football'],
'bar': ['cricket']
}
有沒有更快的方法得到的結果還是可以的我使用一些python builtin函數來處理這種情況?