我的代码存在问题
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'}}}
任何人都可以帮我这个吗?
答案 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'}]}}
免责声明!这会就地修改s1
(pop
会改变该子句,并返回该键的值(如果存在)。
要处理KeyErrors,您可以提供合适的默认值 - s.pop('cloud', 'default')
其中default
是cloud
密钥不存在时返回的值。
答案 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'}]}}