如何迭代 loist 使其值作为我在 python 中的嵌套字典
我不会继续前进,需要一些帮助(我是编码新手)
我有以下结构:
sim = {'S1': {}, 'S2': {}, 'S3': {}, “S4”:{}、“S5”:{}}
和一个列表 sim_list = [1,2,3,4,5]
我的结果应如下所示:
sim = {'S1': {"number": 1}, 'S2': { “number”:2},“S3”:{“number”:3},“S4”:{“number”:4},“S5”:{“number”:5}}
我的尝试:
for key in sim.keys():
for i in sim_list:
sim[key]= {"number":i}
但我只使用 {"number":5} 获取内部字典:
sim = {'S1': {"number": 5}, 'S2': {"number": 5}, 'S3': {"number" : 5}, 'S4': {"number": 5}, 'S5': {"number": 5}}
那么我如何迭代列表对象以转到它们各自的位置?
I am not moving forward and need som help (I'm new to coding)
I have the following structure:
sim = {'S1': {}, 'S2': {}, 'S3': {}, 'S4': {}, 'S5': {}}
and a listsim_list = [1,2,3,4,5]
my result should look like this:
sim = {'S1': {"number": 1}, 'S2': {"number": 2}, 'S3': {"number": 3}, 'S4': {"number": 4}, 'S5': {"number": 5}}
my attempt:
for key in sim.keys():
for i in sim_list:
sim[key]= {"number":i}
but i only get inner dicts with {"number":5}:
sim = {'S1': {"number": 5}, 'S2': {"number": 5}, 'S3': {"number": 5}, 'S4': {"number": 5}, 'S5': {"number": 5}}
so how can i iterate over the list objects to go to their respective place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用字典理解:
不使用字典理解的等效方法是:
也可以使用
zip()
,将每个键和项目关联在一起:Using dict comprehension:
The equivalent without dict comprehension would be:
It is also possible to use
zip()
, to associate each key and item together:或者您可以使用字典理解从头开始构建字典:
输出:
Or you could build the dictionary from scratch using a dictionary comprehension thus:
Output: