[Tutor] Update values stored as a list in a dictionary with valuesfrom another dictionary

Alan Gauld alan.gauld at btinternet.com
Tue Oct 2 10:44:51 CEST 2007


"GTXY20" <gtxy20 at gmail.com> wrote

> Let's say I have the following dictionary:
>
> {1:(a,b,c), 2:(a,c), 3:(b,c), 4:(a,d)}
>
> I also have another dictionary for new value association:
>
> {a:1, b:2, c:3}

I assume the keys should be strings: 'a','b','c'?
Not the variable names a,b,c?

> How should I approach if I want to modify the first dictionary to 
> read:
>
> {1:(1,2,3), 2:(1,3), 3:(2,3), 4:(1,d)}

Lets make life easier by naming the dicts d1,d2 and d3 respectively.
So you want d3 to hold

1: (d2[d1[1][0]], d2[d1[1][1]],d2[d1[1][2]]),
2: (d2[d1[2][0]], d2[d1[2][1]]),
3: (d2[d1[3][0]], d2[d1[3],[1]])

Do you see a pattern?

d3[key] = d2[d1[key][0...len(d1[key])-1]

> There is the potential to have a value in the first dictionary that 
> will not
> have an update key in the second dictionary hence in the above 
> dictionary
> for key=4 I still have d listed as a value.

Look at the get() method of dictionaries to deal with that issue.

You still need to resolve the problem of inconsistent keys if the
d2 keys and d1 values are not strings. That is more tricky!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list