Py学习  »  Python

如何使用列表在python中添加新键和值?[闭门]

user12217822 • 2 年前 • 793 次点击  

我有一本字典和一份清单。 我想向字典中添加一个新键,这样每个键的值都等于一个数组元素。我在下面的例子中对此做了更多解释

我的字典

[{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3}
]

我的名单

['a','b','c']

我想要的是:

[{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1 , 'content' ='a'},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2,  'content' ='b'},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3,  'content' ='c'}
]
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128610
 
793 次点击  
文章 [ 2 ]  |  最新文章 2 年前
no comment
Reply   •   1 楼
no comment    2 年前

压缩并分配:

for d, d['content'] in zip(dicts, contents):
    pass

演示( Try it online! ):

import pprint

dicts = [{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3}
]
contents = ['a','b','c']

for d, d['content'] in zip(dicts, contents):
    pass

pprint.pp(dicts)

输出:

[{'url': 'https://test.com/find/city-1',
  'tit': 'title1',
  'val': 1,
  'content': 'a'},
 {'url': 'https://test.com/find/city-2',
  'tit': 'title1',
  'val': 2,
  'content': 'b'},
 {'url': 'https://test.com/find/city-3',
  'tit': 'title1',
  'val': 3,
  'content': 'c'}]
Alain T.
Reply   •   2 楼
Alain T.    2 年前

您可以使用zip将字典与内容字符串配对,并为每个字符串设置“内容”键:

dicList = [{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1},
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2},
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3}
]
contents = ['a','b','c']
for d,c in zip(dicList,contents):
    d['content'] = c

print(dicList)

[{'url': 'https://test.com/find/city-1', 'tit': 'title1', 'val': 1, 'content': 'a'}, 
 {'url': 'https://test.com/find/city-2', 'tit': 'title1', 'val': 2, 'content': 'b'}, 
 {'url': 'https://test.com/find/city-3', 'tit': 'title1', 'val': 3, 'content': 'c'}]

或者,如果您希望结果出现在一个新的列表中,您可以使用列表理解来构建扩充字典:

dicList2 = [{**d, 'content':c} for d,c in zip(dicList,contents)]