我有一个dicts列表
[
{"day":"10", "car":"bmw", "count":"3"},
{"day":"10", "car":"audi", "count":"2"},
{"day":"10", "car":"jeep", "count":"4"},
{"day":"11", "car":"bmw", "count":"6"},
{"day":"11", "car":"audi", "count":"7"},
{"day":"11", "car":"jeep", "count":"8"},
]
我想将它转换为这样(所需的输出)
[
{"day":"10", "bmw":"3","audi":"2","jeep":"4"},
{"day":"11","bmw":"6","audi":"7","jeep":"8"},
]
这就是我所做的。是否有更好和最佳的方法来实现这一目标。
def dl():
list_of_dicts = [
{"day":"10", "car":"bmw", "count":"3"},
{"day":"10", "car":"audi", "count":"2"},
{"day":"10", "car":"jeep", "count":"4"},
{"day":"11", "car":"bmw", "count":"6"},
{"day":"11", "car":"audi", "count":"7"},
{"day":"11", "car":"jeep", "count":"8"},
]
result = []
data = {}
for item in list_of_dicts:
if not data.get(item["day"], False):
data[item["day"]] = []
data[item["day"]].append({item["car"]:item["count"]})
else:
data[item["day"]].append({item["car"]:item["count"]})
for key in data:
new_dict = {}
new_dict["day"] = key
for item in data[key]:
new_dict.update(item)
result.append(new_dict)
print result
return result
dl()
如果问题不正确,有人请帮助我
更正此问题。我是初学者
答案 0 :(得分:-1)
使用itertools.groupby
根据当天分组,然后为每一天创建一个新的词典:
list_of_dicts = [
{"day":"10", "car":"bmw", "count":"3"},
{"day":"10", "car":"audi", "count":"2"},
{"day":"10", "car":"jeep", "count":"4"},
{"day":"11", "car":"bmw", "count":"6"},
{"day":"11", "car":"audi", "count":"7"},
{"day":"11", "car":"jeep", "count":"8"},
]
# to use groupby the list must be sorted
list_of_dicts.sort(key=operator.itemgetter("day"))
result_list = []
for day, dicts_for_that_day in itertools.groupby(list_of_dicts, key=operator.itemgetter("day")):
day_dict = {'day': day}
day_dict.update({d['car']: d['count'] for d in dicts_for_that_day})
result_list.append(day_dict)
print(result_list)