简体   繁体   中英

append values to a dict in python

I have a list of dictionaries -

list1 = [{'id' : '1', 'b' : '2', 'c' : '3'}, {'id' : '4', 'b' : '5', 'c' : '6'}, {'id' : '7', 'b' : '8', 'c' : ''}]

Based on the value of c being null or not, I am making a call which returns -

list2 - {'d' : '30', 'id' : 1}, {'d': '25', 'id' : '4'}

Now I want to modify list1, so that the final list has the values of d for the ids which have c. For example -

list1 = [{'id' : '1', 'b' : '2', 'c' : '3', 'd' : '30'}, {'id' : '4', 'b' : '5', 'c' : '6', 'd' : '25'}, {'id' : '7', 'b' : '8', 'c' : ''}]

My approach -

for l in list2:
  current_list = {}
  for l2 in list1:
    if l2['id'] == l['id']:
      current_list = l2
      break
    if current_list:
      current_list['d'] = l['d']

Here the actual dict is not getting modified. How can I modify the actual list? Also, is there a neater way to do this?

I'm not certain I understand what you are trying to accomplish. Your written description of your goal does not agree with you code. Based on the code, I'm guessing that you want to match up the data based on the id values.

# You've got some dicts.
dicts = [
    {'id': '1', 'b': '2', 'c': '3'},
    {'id': '4', 'b': '5', 'c': '6'},
    {'id': '7', 'b': '8', 'c': ''},
]

# You've got some other dicts having the same IDs.
d_dicts = [
    {'d': '30', 'id': '1'},
    {'d': '25', 'id': '4'},
]

# Reorganize that data into a dict, keyed by ID.
dlookup = {d['id'] : d['d'] for d in d_dicts}

# Now add that lookup data to the main list of dicts.
for d in dicts:
    i = d['id']
    if i in dlookup:
        d['d'] = dlookup[i]

Assuming mr FMc are correct, there is in python 3.5 a valid approach to merge dicts. Which in this case would led us to:

dicts = [
        {'id': '1', 'b': '2', 'c': '3'},
        {'id': '4', 'b': '5', 'c': '6'},
        {'id': '7', 'b': '8', 'c': ''},
    ]

    d_dicts = [
        {'d': '30', 'id': '1'},
        {'d': '25', 'id': '4'},
    ]

dicts = [{**d, **dict(*filter(lambda x: x["id"] == d["id"], d_dicts))} for d in dicts]

I like these kinda expressions instead of writing it all out, but it has the "benefit" of crashing instead of overwriting stuff when there is more then one dict with the same id. But my solution still overwrites values if there are duplicate keys silently. The inserted value being the value from whatever's second in the dict merge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM