使用python中的动态键和值更新字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13860026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
update dictionary with dynamic keys and values in python
提问by user850287
I have a dictionary and I want to insert keys and values dynamically but I didn't manage to do it. The problem is that when I use the update method it doesn't add a pair but it deletes the previous values so I have only the last value when printing the dictionary here is my code
我有一本字典,我想动态插入键和值,但我没能做到。问题是,当我使用 update 方法时,它不会添加一对,但会删除以前的值,因此在打印字典时我只有最后一个值,这里是我的代码
i = 0
for o in iterload(f):
i=i+1
mydic = {i : o["name"]}
mydic.update({i : o["name"]})
for k, v in mydic.items():
print(k,v)
print(mydic)
f is a file that i'm parsing with python code as a result I get
f 是我用 python 代码解析的文件,结果我得到
{3: 'toto'}
which is the last element. is there a solution to have all the elements in my dictionary
这是最后一个元素。有没有办法在我的字典中包含所有元素
Thanks in advance
提前致谢
I have another question
我有另一个问题
Now I need to chek if an input value equals a key from my dictionary and if so I need to get the value of this key to continue parsing the file and get other informations.
现在我需要检查输入值是否等于我字典中的键,如果是,我需要获取此键的值以继续解析文件并获取其他信息。
Here is my code :
这是我的代码:
f = open('myfile','r')
nb_name = input("\nChoose the number of the name :")
for o in iterload(f):
if o["name"] == mydic[nb_name]:
...
I get a keyError
我收到一个 keyError
Traceback (most recent call last):
File ".../test.py", line 37, in <module>
if o["name"] == mydic[nb_name]:
KeyError: '1'
I don't understand the problem
我不明白这个问题
采纳答案by NPE
Remove the following line:
删除以下行:
mydic = {i : o["name"]}
and add the following before your loop:
并在循环之前添加以下内容:
mydic = {}
Otherwise you're creating a brand new one-element dictionary on every iteration.
否则,您将在每次迭代中创建一个全新的单元素字典。
Also, the following:
此外,以下内容:
mydic.update({i : o["name"]})
is more concisely written as
更简洁地写为
mydic[i] = o["name"]
Finally, note that the entire loop can be rewritten as a dictionary comprehension:
最后,请注意,整个循环可以重写为字典推导式:
mydic = {i+1:o["name"] for i,o in enumerate(iterload(f))}
回答by jfs
@NPE pointed out the problemin your code (redefining the dict on each iteration).
@NPE 指出了您代码中的问题(在每次迭代时重新定义 dict)。
Here's one more way to generate the dict (Python 3 code):
这是生成字典的另一种方法(Python 3 代码):
from operator import itemgetter
mydict = dict(enumerate(map(itemgetter("name"), iterload(f)), start=1))
About the KeyError: '1': input()returns a string in Python 3 but the dictionary mydictexpects an integer. To convert the string to integer, call int:
关于KeyError: '1':input()在 Python 3 中返回一个字符串,但字典mydict需要一个整数。要将字符串转换为整数,请调用int:
nb_name = int(input("\nChoose the number of the name :"))
回答by HelpNeeder
You could use len()to insert the value:
您可以使用len()插入值:
#!/usr/bin/python
queue = {}
queue[len(queue)] = {'name_first': 'Jon', 'name_last': 'Doe'}
queue[len(queue)] = {'name_first': 'Jane', 'name_last': 'Doe'}
queue[len(queue)] = {'name_first': 'J', 'name_last': 'Doe'}
print queue

