简体   繁体   English

创建一个 Python 字典,其中每个键都有一个列表作为值

[英]create a Python dictionary where for each key has a list as the value

I am trying to create a dictionary below with the results to like;我正在尝试在下面创建一个字典,结果很喜欢;

{'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7'}
list1 = ('1','2','3','4','5','6','7')
counter = 0
for x in list1:
    counter =  counter+1
    d = {
        x:counter
    }

but the results I am getting are: {'7': 7}但我得到的结果是: {'7': 7}

Use a dict comprehension:使用 dict 理解:

d = {x: int(x) for x in list1}

or或者

d = {x: i+1 for i, x in enumerate(list1)}

If you want to still have the loop, try:如果你想仍然有循环,请尝试:

list1 = ('1','2','3','4','5','6','7')
counter = 0
for x in list1:
    counter =  counter+1
    d[x] = counter

or d.update({x: counter}) instead of d[x] = counter .d.update({x: counter})而不是d[x] = counter

You are reassigning d on every iteration.您在每次迭代时重新分配d

Either way, you can do this with a dictionary comprehension and enumerate :无论哪种方式,您都可以通过字典理解和enumerate来做到这一点:

>>> list1 = ('1','2','3','4','5','6','7')
>>> d = {x: counter for counter, x in enumerate(list1, 1)}
{'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7}
dict1 = { x: int(x) for x in list1 }

You create a new dict each time你每次创建一个新的字典

Start one and add to it开始一个并添加到它

d = {}
for foo in bar:
    d[foo] = baz

That is because you erase the variable d at each iteration.那是因为您在每次迭代时都删除了变量d

You want to add the new key and value to an already existing dictionary (created empty: d = {} ), with d[x] = counter .您想使用d[x] = counter将新键和值添加到已经存在的字典(创建为空: d = {} )。

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

相关问题 Python从具有key:value字符串的列表中创建字典 - Python create dictionary from a list that has key:value strings 从多个列表创建字典,其中每个列表没有一个键的值,但每个列表都有所有键的值 - create dictionary from multiple lists, where each list has not the values for one key, but each list has values for all keys python 更新列表中字典的每个键值 - python updating each key value of dictionary in list 如何将Python中的数据列表转换为每个项目都有一个键的字典 - How to convert a list of data in Python to a Dictionary where each item has a key 创建一个 python 字典,其中值是字符串列表 - create a python dictionary where the value is a list of strings 如何将 CSV 读入 Python 字典,其中每个键的值都是字典列表? - How can I read a CSV into a Python dictionary, where each key's value is a list of dicts? Python - 每个字典值都是一个列表的唯一字典列表 - Python - List of unique dictionaries where each dictionary value is a list Python 字典包含列表作为值 - 如何为每个键添加值? - Python Dictionary Contains List as a Value - How to add the value for each key? Python字典理解:将值分配给键,其中值是一个列表 - Python dictionary comprehension: assign value to key, where value is a list 在 Python 中的字典列表中拆分每个键的值 - Splitting each key's value in a list of a dictionary in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM