当我尝试合并两个字典以适合稍后发布时,我遇到了问题。由于某种原因,get似乎是嵌套的,我不知道如何清理它。很高兴得到一些关于优化代码的技巧,现在它看起来有点乱。
class DownloadHelper{
public DownloadHelper(){
}
public void performTask(){
----
----
}
}
网络:
for network in networks:
post_dict = {e1:e2 for e1,e2 in network['extattrs'].iteritems() if e1 not in keys }
pprint (post_dict['Stuff-Name']['value'])
post_dict['name'] = post_dict.pop('Stuff-Name')
post_dict['sid'] = post_dict.pop('Stuff-id')
dict_to_post = merge_two_dicts(post_dict, default_keys)
default_keys:
{u'_ref': u'ref number',
u'comment': u'Name of object',
u'extattrs': {u'Network-Type': {u'value': u'Internal'},
u'Stuff-Id': {u'value': 110},
u'Stuff-Name': {u'value': u'Name of object'}},
u'network': u'Subnet-A',
u'network_view': u'default'}
post_dict:
default_keys = {'status':'Active',
'group':None,
'site':'City-A',
'role':'Production',
'description':None,
'custom_fields':None,
'tenant':None}
所以我想要实现的是摆脱嵌套密钥(在密钥“name”和“sid”中,因此密钥和值对应该是“name:object of object”和“sid:110”
尚未定义帖子功能。
答案 0 :(得分:0)
要获取任何嵌套字典的第一个值,您可以使用此
d = {'custom_fields': None, 'description': None, 'group': None, 'name':
{'value': 'Name of object'}, 'role': 'Production', 'site': 'City-A',
'status': 'Active', 'tenant': None, 'sid': {'value': 110}}
for key in d.keys():
if type(d[key]) == dict:
d[key] = d[key].popitem()[1]
返回
{'custom_fields': None, 'description': None, 'group': None, 'name': 'Name of
object', 'role': 'Production', 'site': 'City-A', 'status': 'Active',
'tenant': None, 'sid': 110}
我认为正是这一步导致字典首先嵌套
post_dict['name'] = post_dict.pop('Stuff-Name')
post_dict['sid'] = post_dict.pop('Stuff-id')
如果您只需要该字典的值而不是密钥,可以尝试使用popitem()[1]。
答案 1 :(得分:0)
根据我的理解,你的情况非常具体,我可能会选择一个简单的方法。肮脏的解决首先,你试过这个:
post_dict['name'] = (post_dict.pop('Stuff-Name'))['value']
其次,如何利用“过滤和重命名”并在那里折叠索引?这是不可取的,但是如果你想做一个懒惰的解决方案就足够了。我建议你继续我的第一个建议,因为我非常有信心它会解决你的问题。