有没有办法在for循环中加入字典。 这是我的示例代码:
for value in data['actions']:
if 'remoteUrls' in value:
url = value['remoteUrls']
ref = value['lastBuiltRevision']['SHA1']
new_dict['url'] = url
new_dict['ref'] = ref
print new_dict
结果:
{
'url': [u'ssh://abc.com:29418/abc.git'],
'ref': u'194d4c418c71f77355117bd253cf2ac9849b25dd'
}
{
'url': [u'ssh://def:29418/def.git'],
'ref': u'7a198bf01b73330c379cc54aae1631f4448a4b0b'
}
我想将结果合并到一个字典中,所需的输出是这样的:
{
vcs1: {
'url': [u'ssh://abc.com:29418/abc.git'],
'ref': u'194d4c418c71f77355117bd253cf2ac9849b25dd'
},
vcs2: {
'url': [u'ssh://def:29418/def.git'],
'ref': u'7a198bf01b73330c379cc54aae1631f4448a4b0b'
}
}
有没有办法达到预期的输出?任何帮助,将不胜感激。谢谢。
答案 0 :(得分:2)
这是一种方式:
lst = [{'url': [u'ssh://abc.com:29418/abc.git'],'ref':u'194d4c418c71f77355117bd253cf2ac9849b25dd'},
{'url': [u'ssh://def:29418/def.git'], 'ref': u'7a198bf01b73330c379cc54aae1631f4448a4b0b'}]
i = (i for i in range(len(lst)))
d = {'vcs{}'.format(next(i) + 1): x for x in lst}
print(d)
# {'vcs1': {'url': ['ssh://abc.com:29418/abc.git'], 'ref': '194d4c418c71f77355117bd253cf2ac9849b25dd'},
# 'vcs2': {'url': ['ssh://def:29418/def.git'], 'ref': '7a198bf01b73330c379cc54aae1631f4448a4b0b'}}
或使用评论中建议的itertools.count
:
from itertools import count
lst = [{'url':[u'ssh://abc.com:29418/abc.git'],'ref':u'194d4c418c71f77355117bd253cf2ac9849b25dd'},
{'url': [u'ssh://def:29418/def.git'], 'ref': u'7a198bf01b73330c379cc54aae1631f4448a4b0b'}]
i = count(1)
d = {'vcs{}'.format(next(i)): x for x in lst}
print(d)
# {'vcs1': {'url': ['ssh://abc.com:29418/abc.git'], 'ref': '194d4c418c71f77355117bd253cf2ac9849b25dd'},
# 'vcs2': {'url': ['ssh://def:29418/def.git'], 'ref': '7a198bf01b73330c379cc54aae1631f4448a4b0b'}}
或者使用enumerate
:
d = {'vcs{}'.format(i): x for i, x in enumerate(lst, 1)}
答案 1 :(得分:0)
有一些简单的方法,
>>> a = dict() >>> a.update({1:2}) >>> a {1: 2} >>> a.update({3:4}) >>> a {1: 2, 3: 4}
>>> a['key123'] = {'url':['url1','url2'], 'ref':'REF'} >>> a {1: 2, 'key1': {'a': 'hello'}, 3: 4, 'key123': {'url': ['url1', 'url2'], 'ref': 'REF'}, 'key2': {'url': ['URL1', 'URL2'], 'ref': u'ref'}}
根据您的情况,
res = dict()
for value in data['actions']:
if 'remoteUrls' in value:
res['key_name'] = {'url':value['remoteUrls'] ,
'ref':value['lastBuiltRevision']['SHA1']}
print res # check the entries
dict(dict(<key>, {'url':value['remoteUrls'], 'ref':value['lastBuiltRevision']['SHA1']} for value in data['actions'] if 'remoteUrls' in value)