简体   繁体   English

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

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

Question: Given a list named list1 and a dictionary named dict1 , using "For" loop to write code to add all items of list1 to dict1 by using the index of the list as the key of the dictionary and the item of the list as the value of the dictionary. 问:给定一个list命名list1和字典命名dict1 ,使用“for”循环编写代码来添加的所有项目list1dict1使用的索引list作为字典的关键和的项目list作为字典的值。 for example: 例如:

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

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

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

My Code: 我的代码:

`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)`

2nd attempt after 1 desperate hour of trying: 经过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)`

I'm lost! 我迷路了!

Do like this, 这样吧

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

or 要么

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