0

I have the following code implemented with result getting produced as 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

        # for tenant and instance combinations dict
        for a,b in tenant_server_combination.iteritems():

                for 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 is having one more entry: 'new_ins_1'

Current code which I have created overwrite the value based on Key.

Now I need the way to achieve the result which is as follows:

{'b0116ce25cad4106becbbddfffa61a1c': ['demo_ins1'],'1578f81703ec4bbaa1d548532c922ab9': ['new_ins_1','new_tenant_ins']}
iamnewuser
  • 360
  • 1
  • 4
  • 16
  • 1
    Possible duplicate of [append multiple values for one key in Python dictionary](http://stackoverflow.com/questions/3199171/append-multiple-values-for-one-key-in-python-dictionary) – smac89 Jan 29 '16 at 04:47

1 Answers1

2

You can use collections.defaultdict with a list as the default. For example:

In [17]: from collections import defaultdict

In [18]: d = defaultdict(list)

In [19]: import random

In [20]: for _ 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]})
Randy
  • 14,349
  • 2
  • 36
  • 42
  • Can you be able to propose the solution for above code instead of example – iamnewuser Jan 29 '16 at 03:30
  • 1
    Initialize `tenant_id_dict = defaultdict(list)` and change `tenant_id_dict[a] = server` to `tenant_id_dict[a].append(server)` – Randy Jan 29 '16 at 03:32