我有以下包含每年家庭ID(HID)的词典列表:
list_of_dicts = [{'HID':'1','year':'2017'},
{'HID':'1','year':'2018'},
{'HID':'2','year':'2017'},
{'HID':'2','year':'2018'},
{'HID':'3','year':'2017'},
{'HID':'3','year':'2018'}]
我想在每个dict中读取并添加一个新的数字ID。我可以使用以下代码执行类似的操作:
i = 0
for line in list_of_dicts:
line['id'] = i
i += 1
然而,这会使id
项目连续运行:
list_of_dicts = [{'HID':'1','year':'2017','id':1},
{'HID':'1','year':'2018','id':2},
{'HID':'2','year':'2017','id':3},
{'HID':'2','year':'2018','id':4},
{'HID':'3','year':'2017','id':5},
{'HID':'3','year':'2018','id':6}]
我希望每年为每个HID分配相同的数字id
变量,如下所示:
list_of_dicts = [{'HID':'1','year':'2017','id':1},
{'HID':'1','year':'2018','id':1},
{'HID':'2','year':'2017','id':2},
{'HID':'2','year':'2018','id':2},
{'HID':'3','year':'2017','id':3},
{'HID':'3','year':'2018','id':3}]
如何控制每个家庭每年的ID分配是否相同?
答案 0 :(得分:1)
您需要将其更改为不基于i
。而是这样做:
for line in list_of_dicts:
line['id'] = line['hid']
这样您就可以根据该行的id
创建新条目hid
答案 1 :(得分:1)
在Python3中,您可以使用列表推导和字典解包:
list_of_dicts = [{'HID':'1','year':'2017'},
{'HID':'1','year':'2018'},
{'HID':'2','year':'2017'},
{'HID':'2','year':'2018'},
{'HID':'3','year':'2017'},
{'HID':'3','year':'2018'}]
new_data = [{**i, **{'id':i['HID']}} for i in list_of_dicts]
输出:
[{'HID': '1', 'year': '2017', 'id': '1'}, {'HID': '1', 'year': '2018', 'id': '1'}, {'HID': '2', 'year': '2017', 'id': '2'}, {'HID': '2', 'year': '2018', 'id': '2'}, {'HID': '3', 'year': '2017', 'id': '3'}, {'HID': '3', 'year': '2018', 'id': '3'}]
答案 2 :(得分:0)
这是你在找什么?
list_of_dicts = [{'HID':'1','year':'2017'},
{'HID':'1','year':'2018'},
{'HID':'2','year':'2017'},
{'HID':'2','year':'2018'},
{'HID':'3','year':'2017'},
{'HID':'3','year':'2018'}]
for line in list_of_dicts:
line['id'] = line['HID']
print(list_of_dicts)
输出:
[{'HID': '1', 'year': '2017', 'id': '1'}, {'HID': '1', 'year': '2018', 'id': '1'}, {'HID': '2', 'year': '2017', 'id': '2'}, {'HID': '2', 'year': '2018', 'id': '2'}, {'HID': '3', 'year': '2017', 'id': '3'}, {'HID': '3', 'year': '2018', 'id': '3'}]