views:

168

answers:

1

Is there a better way to express this using list comprehension? Or any other way of expressing this in one line?

I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the col dictionary.

col = {'1':3.5, '6':4.7}
original = {'1':3, '2':1, '3':5, '4':2, '5':3, '6':4}
for entry in col.iteritems():
    original[entry[0]] = entry[1]
+2  A: 

I believe update is what you want.

update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

Code:

original.update(col[user])

A simple test:

user = "user"

matrix = {
    "user" : {
        "a" : "b",
        "c" : "d",
        "e" : "f",
    },
}

col = {
    "user" : {
        "a" : "b_2",
        "c" : "d_2",
    },
}

original.update(col[user])

print(original)

Output

{'a': 'b_2', 'c': 'd_2', 'e': 'f'}
Ionuț G. Stan
awesome! I just learned another useful shortcut.
Pavel
The question says "I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the col dictionary." Won't this violate the second half of that statement?
Steve Losh
Oh, nevermind. I think I read the question incorrectly... `col` is the dictionary used to update, not the one being updated.
Steve Losh
@Steve, no. According to the manual, it only overrides existing keys. So any key/value pair in `original` is left untouched if there is no correspondent key in `col[user]`. In my example this was `"e" : "f"`.
Ionuț G. Stan