繁体   English   中英

如何通过使用列表的索引作为键和列表的项作为值来将列表添加到字典?

[英]How to add list to dictionary by using index of list as key and item of list as value?

问:给定一个list命名list1和字典命名dict1 ,使用“for”循环编写代码来添加的所有项目list1dict1使用的索引list作为字典的关键和的项目list作为字典的值。 例如:

`    list1 = ["a","b","c"]`

`    dict1 = {7:"d",8:"e",9:"f"}`

运行代码后, dict1 = {7:"d",8:"e",9:"f",0:"a",1:"b",2:"c"}

我的代码:

`dict1 = {7:"d", 8:"e", 9:"f"}
list1 = ["a", "b", "c"]
ii = 0
for i in [dict1]:
    dict1[ii] = list1[ii]
    ii = ii + 1
    print(dict1)`

经过1个绝望小时的尝试:

`for i in list1:
    if i not in dict1.keys():
        dict1[0] = list1[0]
        dict1[1] = list1[1]
        dict1[2] = list1[2] 
        print(dict1)`

我迷路了!

这样吧

>>> list1 = ["a","b","c"]
>>> dict1 = {7:"d",8:"e",9:"f"}
>>> dict1.update(dict(enumerate(list1)))
>>> dict1
{0: 'a', 1: 'b', 2: 'c', 7: 'd', 8: 'e', 9: 'f'}

要么

>>> dict(dict1.items() + list(enumerate(list1)))
{0: 'a', 1: 'b', 2: 'c', 7: 'd', 8: 'e', 9: 'f'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM