简体   繁体   English

如何为字典Python添加值

[英]How to add values to Dictionary Python

Sorry if this is a noob question but I am new to programming and python that is why I am asking. 抱歉,如果这是一个菜鸟问题,但是我是编程和python的新手,这就是为什么我要问这个问题。

I want to add values to my dictionary keys. 我想将值添加到字典键中。

I have dictionary: 我有字典:

dictio = {"Object": "Computer"}

Now within the key "Object" , I would like to add the value "Mouse" . 现在,在键“ Object”中 ,我想添加值“ Mouse”

So the end result i am looking for is: 所以我寻找的最终结果是:

>>> dictio
>>> {"Object": ["Computer", "Mouse"]}

Your formulation seems to show you didn't grasp correctly what are dict in python. 您的表述似乎表明您没有正确理解python中的dict是什么。 This also makes it difficult for us to understand what you want. 这也使我们很难理解您想要什么。

For instance: 例如:

I want to add values to my dictionary keys.

Is ambiguous (at least) and could be interpreted in several ways. (至少)是模棱两可的,可以用几种方式解释。 I'll explain what is ambiguous in the following answer. 我将在以下答案中解释什么是模棱两可的。

Even your original example was not helping, as it is not valid syntax: 甚至您原来的示例也无济于事,因为它不是有效的语法:

>>> {"Object": "Computer", "Mouse"}
SyntaxError: invalid syntax

The vocabulary of dict is about key and values . 字典的词汇是关于值的

In a dict every key has a value and only one . 字典的每个都有一个 ,只有一个

So here's the question you'll have to answer: What is "Mouse" ? 因此,这是您必须回答的问题:什么是"Mouse" a key or a value of dictio , or none of them ? dictio ,还是都不是?

Either you wanted: 您想要的是:

>>> {"Object": "Computer", "Mouse": "A Sample Value"}

Which is a dictionary with a new pair of key / value . 这是一本带有一对新的 / 对的字典。 It can be done like this: 可以这样完成:

>>> dictio["Mouse"] = "A Sample Value"

Or perhaps you wanted to 'add' another value to the already stored value for the key "Object" in the dictionary. 或者,您可能想将另一个 “添加”到字典中键"Object"的已存储中。 But 'adding' a value is ambiguous when speaking of a value in a dict , as dictionaries holds only one value for one key ! 但是当说字典中的一个时,“添加”一个是模棱两可的,因为字典的一个只拥有一个

  • Do you want the current string value to be concatenated with a new one ? 您是否希望将当前字符串 与一个新的字符串连接起来?
  • Or do you want to replace the current string value with a list of values ? 还是要用 列表替换当前字符串 (If yes, your starting value should have been a list of one element in the first place). (如果是的话,你的初始应该是一个元素摆在首位的列表 )。

The resulting dict using a list as value for the key "Object" would be: 使用列表作为 "Object" 的结果字典为:

>>> {"Object": ["My Computer", "Mouse"]}

So this would remain a one key dict , with one value . 因此,这将仍然是一 字典 ,只有一个 This value happens to be a list of value , it means that it self, it can hold several inner values in a specific order. 恰好是列表 ,这意味着它的自我,它可以在一个特定的顺序保持几个内在价值

Notice that if I want to start from your original dictio to get the previous result, I have to replace the value "Computer" (of type string ) with a different value of different type: ["My Computer", "Mouse"] (it is a list of values). 请注意,如果我想从原始的dictio开始以获得先前的结果,则必须用不同类型的其他值替换"Computer"string类型的值): ["My Computer", "Mouse"] (它是值列表 )。

So this could be done like this: 所以可以这样做:

>>> dictio["Object"] = [dictio["Object"], "Mouse"]

But, this is not very natural and you would probably want to start with a dictio like this: 但是,这不是很自然,您可能想从这样的dictio开始:

>>> dictio = {"Object": ["Mouse"]}

Then, 'adding' a value to a list is not anymore ambiguous. 然后,将 “添加”到列表不再是模棱两可的。 And then it would also be simpler to achieve: 然后它也将更容易实现:

 >>> dictio["Object"].append("Mouse") 

I hope reading this helped you to better grasp what are dicts in python. 希望看完这有助于你更好地把握什么是蟒蛇类型的字典 You should probably find tutorials or basic docs about dictionaries as you seem to have missed some fundamental notions. 您似乎应该找到有关字典的教程或基本文档,因为您似乎错过了一些基本概念。

One possible approach: 一种可能的方法:

dictio = {"Object": ["Computer"]}

dictio["Object"].append("mouse")

You cannot perform a list operation on a string: 您不能对字符串执行列表操作:

>>> 'string'.append('addition')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

You can only add something to the data structure if the addition is supported: 如果支持添加,则只能将某些内容添加到数据结构中:

>>> li=['string']
>>> li.append('addition')
>>> li
['string', 'addition']

You want to take a dict composed of a string associated with another string: 您要采用由与另一个字符串关联的字符串组成的字典:

dictio = {"Object": "Computer"}

And add to it as if it were a list. 然后将其添加为列表。 Same problem as above: 与上述相同的问题:

>>> dictio["Object"].append("Mouse")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

What to do? 该怎么办? If the object in the dict is a string, it needs to be a list to append to it. 如果字典中的对象是字符串,则它必须是要附加到其上的列表。

You can test first: 您可以先测试:

>>> if isinstance(dictio["Object"], list): 
...    dictio["Object"].append('Mouse')
... else:
...    dictio["Object"]=[dictio["Object"]]
...    dictio["Object"].append('Mouse')
... 
>>> dictio
{'Object': ['Computer', 'Mouse']}

Or try it and react to failure: 或者尝试一下,对失败做出反应:

try:
    dictio["Object"].append("Mouse")
except AttributeError:
    dictio["Object"]=[dictio["Object"]]
    dictio["Object"].append("Mouse")    

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

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