将新项添加到基于其他项值控制的词典列表

时间:2018-04-24 19:48:50

标签: python list dictionary

我有以下包含每年家庭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分配是否相同?

3 个答案:

答案 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'}]