Python:如何在for循环中加入字典

时间:2018-06-19 10:48:14

标签: python for-loop

有没有办法在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'
    }
}

有没有办法达到预期的输出?任何帮助,将不胜感激。谢谢。

2 个答案:

答案 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)

有一些简单的方法,

  • dict.update()将帮助您加入字典。
>>> a = dict()
>>> a.update({1:2})
>>> a
{1: 2}
>>> a.update({3:4})
>>> a
{1: 2, 3: 4}
  • dict ['key'] = {'url':['URL'],'ref':'REF'}
>>> 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)