[英]converting a list of tuples to list of dictionary in Python
我正在嘗試將元組列表轉換為字典列表,其數據如下所示:
data =[
('base-certificate', 60, 3, 2022),
('case-certificate', 1, 3, 2022),
('standard-certificate', 7, 3, 2022),
('base-certificate', 50, 4, 2022),
('case-certificate', 80, 4, 2022),
('standard-certificate', 10, 4, 2022)
]
最后兩個數字是代表月份和年份的日期,這意味着也可以有 April(4)、May(5) 等的數據,並且是唯一的。 因此,要在 javascript 中創建日期對象,最好在列表 [3, 2022] 中需要這兩個數字。
我想要一個如下所示的輸出:
[
{x:[3, 2022], base: 60, case:1, standard: 7},
{x:[4, 2022], base: 50, case:80, standard: 10}
]
我嘗試使用集合庫中的 defaultdict:
from collections import defaultdict
data=defaultdict(dict)
for a, b, c, d in se:
if "x" not in data[c, d]:
data[c, d]['x'] = [c,d]
data[c, d][a] = b
print(data)
代碼的結果是:
defaultdict(<class 'dict'>, {(3, 2022): {'x': [3, 2022], 'base-certificate': 60, 'case-certificate': 1, 'standard-certificate': 7}, (4, 2022): {'x': [4, 2022], 'base-certificate': 50, 'case-certificate': 80, 'standard-certificate': 10}})
它很接近,但我錯過了一些東西。 請問在這種情況下最好的方法是什么? 我做錯了什么,謝謝您的友好回復。
這是使用itertools.groupby
的可能解決方案。 如果日期已排序,您可以直接在數據上使用groupby
,如果沒有,則應先按日期排序。
from itertools import groupby
result = []
for key, group in groupby(data, lambda x: (x[2], x[3])):
r = {'x': key}
for a, b, _, _ in group:
r[a.partition('-')[0]] = b
result.append(r)
print(result)
輸出:
[{'x': (3, 2022), 'base': 60, 'case': 1, 'standard': 7}, {'x': (4, 2022), 'base': 50, 'case': 80, 'standard': 10}]
嘗試:
data = [
("base-certificate", 60, 3, 2022),
("case-certificate", 1, 3, 2022),
("standard-certificate", 7, 3, 2022),
("base-certificate", 50, 4, 2022),
("case-certificate", 80, 4, 2022),
("standard-certificate", 10, 4, 2022),
]
out = {}
for name, val, month, year in data:
out.setdefault((month, year), {}).update(
{"x": [month, year], name.split("-")[0]: val}
)
print(list(out.values()))
印刷:
[
{"x": [3, 2022], "base": 60, "case": 1, "standard": 7},
{"x": [4, 2022], "base": 50, "case": 80, "standard": 10},
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.