将字典元组转换为嵌套字典

时间:2018-04-20 14:35:23

标签: python python-2.7 dictionary

我的代码存在问题

s1 = ({'server_id':'myserver1','cloud':'google','time':'1hr'},
      {'server_id':'myserver2','cloud':'aws','time':'2hr'},
      {'server_id':'myserver3','cloud':'google','time':'1hr'}
      {'server_id':'myserver4','cloud':'aws','time':'3hr'})
mydict = {'mine':
          {data[i]:
           {key:value for key,value in data.iteritems() if key!='cloud'}
          for data in s1 for i in data if i=='cloud'}}
print mydict

结果:

{'mine': {'aws': {'server_id': 'myserver3','time':'3hr'}}}

但我期待像这样的结果

{'mine':
 {'aws':
  {'server_id': 'myserver1','time':'1hr'},
  {'server_id': 'myserver3','time':'3hr'}},
 {
 'google':
  {'server_id': 'myserver2','time':'2hr'},
  {'server_id': 'myserver4','time':'4hr'}}}

任何人都可以帮我这个吗?

2 个答案:

答案 0 :(得分:4)

考虑初始化字典并在循环内附加到它。使用dict.pop负责删除cloud密钥而不必迭代整个事情,因为您当前正在这样做。

from collections import defaultdict
d = defaultdict(list)  # {}

for s in s1:
    d[s.pop('cloud')].append(s)  # d.setdefault(s.pop('cloud'), []).append(s)

{'mine' : dict(d)}

{'mine': {'aws': [{'server_id': 'myserver1', 'time': '1hr'},
   {'server_id': 'myserver2', 'time': '2hr'},
   {'server_id': 'myserver3', 'time': '3hr'}]}}

免责声明!这会就地修改s1pop会改变该子句,并返回该键的值(如果存在)。

要处理KeyErrors,您可以提供合适的默认值 - s.pop('cloud', 'default')其中defaultcloud密钥不存在时返回的值。

答案 1 :(得分:1)

问题是您正在尝试将三个词典映射到同一个键。如果你把它变成一个词典列表,那就行了。

s1 = ({'server_id':'myserver1','cloud':'aws','time':'1hr'},
      {'server_id':'myserver2','cloud':'aws','time':'2hr'},
      {'server_id':'myserver3','cloud':'aws','time':'3hr'})
mydict = {'mine':
          {data['cloud']:
           [{key:value for key, value in data.iteritems() if key != "cloud"}
            for data in s1]}}
print mydict

输出:

{'mine': {'aws': [{'server_id': 'myserver1', 'time': '1hr'},
   {'server_id': 'myserver2', 'time': '2hr'},
   {'server_id': 'myserver3', 'time': '3hr'}]}}