将值添加到键而不是覆盖 - 在python中的Dict

时间:2016-01-29 03:25:31

标签: python list dictionary

我实现了以下代码,结果如下所示:

代码:

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

实际结果:

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

基本上第二个关键是还有一个条目:'new_ins_1'

我创建的当前代码会根据Key覆盖该值。

现在我需要达到如下结果的方法:

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

1 个答案:

答案 0 :(得分:2)

您可以使用collections.defaultdict作为默认列表。例如:

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]})