list - Add a value to key instead of overwrite - Dict in python -


i have following code implemented result getting produced given below:

code:

for tenant in tenants_list:          tenant_id = tenant.id         server_list = nova.servers.list(search_opts={'all_tenants':1,'tenant_id':tenant_id})         tenant_server_combination[tenant_id] = server_list          # tenant , instance combinations dict         a,b in tenant_server_combination.iteritems():                  server_id in b:                                 server = server_id.name                                 tenant_id_dict[a] = server print tenant_id_dict 

actual result:

{u'b0116ce25cad4106becbbddfffa61a1c': u'demo_ins1', u'1578f81703ec4bbaa1d548532c922ab9': u'new_tenant_ins'} 

basically second key having 1 more entry: 'new_ins_1'

current code have created overwrite value based on key.

now need way achieve result follows:

{'b0116ce25cad4106becbbddfffa61a1c': ['demo_ins1'],'1578f81703ec4bbaa1d548532c922ab9': ['new_ins_1','new_tenant_ins']} 

you can use collections.defaultdict list default. example:

in [17]: collections import defaultdict  in [18]: d = defaultdict(list)  in [19]: import random  in [20]: _ in xrange(100):    ....:     d[random.randrange(10)].append(random.randrange(10))    ....:  in [21]: d   out[21]: defaultdict(<type 'list'>, {0: [4, 3, 2, 1, 4, 7],    1: [5, 1, 3, 4, 4, 2, 2, 1],    2: [2, 4, 0, 0, 8, 6, 1, 0, 2, 4, 8, 0, 1, 2, 5, 4],    3: [5, 0, 5, 4, 7, 6, 9, 3],    4: [7, 3, 7, 7, 1, 2, 8, 4],   5: [6, 4, 4, 1, 4, 8, 5, 9, 4, 8, 3, 3, 1],    6: [1, 7, 8, 6, 9, 5, 6, 5, 8, 4],    7: [2, 6, 8, 7, 7, 3, 5],    8: [7, 9, 2, 0, 2, 1, 8, 0, 5, 6, 7, 1, 7],    9: [9, 6, 5, 2, 8, 8, 0, 2, 7, 5, 3]}) 

Comments