StealthPython StealthPython - 1 month ago 13
Python Question

Updating dictionary with another k/v in python

I hate to ask this but I can't figure it out and it's getting to me.

I have to make a function that takes a given dictionary (d1) and sort of compares it to another dictionary (d2) then adds the compared value to d2.

d1 is already in the format needed to I don;'t have to worry about it.
d2 however, is a nested dictionary. It looks like this:

{’345’: {’Name’: ’xyzzy’, ’ID’: ’345’, ’Responses’: {’Q3’: ’c’, ’Q1’: ’a’, ’Q4’: ’b’, ’Q2’: ’a’}},
’123’: {’Name’: ’foo’, ’ID’: ’123’, ’Responses’: {’Q3’: ’c’, ’Q1’: ’a’, ’Q4’: ’a’, ’Q2’: ’b’}},
’234’: {’Name’: ’bar’, ’ID’: ’234’, ’Responses’: {’Q3’: ’c’, ’Q1’: ’a’, ’Q4’: ’b’, ’Q2’: ’b’}}}


So d1 is in the format of the 'Responses' key, and that's what i need from d2 to compare it to d1.

So to do that I isolate 'responses':

for key, i in d2.items():
temp = i['Responses']


Now I need to run temp through a function with d1 that will output an integer. Then match that integer with the top-level key it came from and update a new k/v entry associated with it. But I don't know how to do this.

I've managed to update each top-level key with that compared value, but it only uses the first compared value for all the top-level keys. I can't figure out how to match the integer found to its key. This is what I have so far that works the best:

for i in d2:
score = grade_student(d1,temp) #integer
placement = {'Score': score}
d2[i].update(placement)

Answer

You could just iterate over sub dictionaries in d2 and update them once you've called grade_student:

for v in d2.values():
    v['Score'] = grade_student(d1, v['Responses'])

Here's a complete example:

import pprint

d1 = {}
d2 = {
    '345': {'Name': 'xyzzy', 'ID': '345', 'Responses': {'Q3': 'c', 'Q1': 'a', 'Q4': 'b', 'Q2': 'a'}},
    '123': {'Name': 'foo', 'ID': '123', 'Responses': {'Q3': 'c', 'Q1': 'a', 'Q4': 'a', 'Q2': 'b'}},
    '234': {'Name': 'bar', 'ID': '234', 'Responses': {'Q3': 'c', 'Q1': 'a', 'Q4': 'b', 'Q2': 'b'}}
}

# Dummy
def grade_student(x, y):
    return 1

for v in d2.values():
    v['Score'] = grade_student(d1, v['Responses'])

pprint.pprint(d2)

Output:

{'123': {'ID': '123',
         'Name': 'foo',
         'Responses': {'Q1': 'a', 'Q2': 'b', 'Q3': 'c', 'Q4': 'a'},
         'Score': 1},
 '234': {'ID': '234',
         'Name': 'bar',
         'Responses': {'Q1': 'a', 'Q2': 'b', 'Q3': 'c', 'Q4': 'b'},
         'Score': 1},
 '345': {'ID': '345',
         'Name': 'xyzzy',
         'Responses': {'Q1': 'a', 'Q2': 'a', 'Q3': 'c', 'Q4': 'b'},
         'Score': 1}}