如何在Python字典中加入循环

2024-09-30 04:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

结果:

^{pr2}$

我想将结果合并到一个字典中,期望的输出如下:

{
    vcs1: {
        'url': [u'ssh://abc.com:29418/abc.git'],
        'ref': u'194d4c418c71f77355117bd253cf2ac9849b25dd'
    },
    vcs2: {
        'url': [u'ssh://def:29418/def.git'],
        'ref': u'7a198bf01b73330c379cc54aae1631f4448a4b0b'
    }
}

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


Tags: 方法ingitrefurl示例newfor
2条回答

有一些简单的方法

  • 在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)

这是一种方法:

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'}}                     

或者使用注释中建议的^{}

^{pr2}$

或者使用^{}这甚至很简单:

^{3}$

相关问题 更多 >

    热门问题