user3043455
user3043455

Reputation: 3

Updating values in multi value dictionary from another dictionary

I have two dictionaries, and I am looking for a way to update values in multi value dictionary IP_list, by checking value in dictionary ID_list. Basically I need to substitute an email string from IP_list by id value from ID_list.

IP_list={'ip1': ['email1', 'string1'], 'ip2': ['email2', 'string2'],'ip3': ['email2', 'string3']}
ID_list={'email1': 'id1', 'email2': 'id2', 'email3': 'id3'}

Expected output:
{'ip1': ['id1', 'string1'], 'ip2': ['id2', 'string2'],'ip3': ['id2', 'string3']}
or the ID value can be added on the end of specific key values as:
{'ip1': ['email1','string1','id1'], 'ip2': ['email2','string2','id2'],'ip3': ['email2','string3','id2']}

Can someone be of any help ?

Thanks J.

Edit:I tried solution suggested by Roman it works on Python 2.7.5 with no problem, but it is giving me hard time to get it working on Python 2.6.6

@Roman, IP_list is created from MSSQL db by:

for row in results:
      IP_list[row.IP_address]= row.email, row.description

print IP_list will give this: on Python 2.7.5 on my dev environment I will get :

{'IP': ('email1', 'description "info"'),'IP2': ('email2', 'description')}

On on production system with Python 2.6.6 I will get some values unicode

{'IP': (u'email1', u'description "info"'),'IP2': (u'email2', u'description')}

so I converted the unicode values to ascii, so there should be no problem.

ID_list is created from XML on output is same on both envinronments:

{'email1': 'id1', 'email2': 'id2', 'email3': 'id3'}

when I run the script on Python 2.7.5 it works fine, but on 2.6.6 it gives me this error

val[0] = ID_list.get(val[0], val[0])
TypeError: 'tuple' object does not support item assignment

Upvotes: 0

Views: 69

Answers (1)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

Something like:

for val in IP_list.itervalues():
    val[0] = ID_list.get(val[0], val[0])

If email from IP_list is missing in the ID_list, it won't be changed.

And now IP_list looks like:

{'ip2': ['id2', 'string2'], 'ip3': ['id2', 'string3'], 'ip1': ['id1', 'string1']}

Upvotes: 1

Related Questions