消除python中字典中的重复 [英] Eliminating repetition among the dictionary in python
问题描述
我正在python中创建一个字典,但是列表和python之间的细节让我很困惑。我有什么是
I am working on creating a dictionary in python but the thin line between list and python is confusing me alot. What i have is
values = []
我将把这些值存储为
values.append({newvalue:oldvalue})
列表或字典不管它是什么,它正在工作,但不检查它们之间的重复。所以我做的是
the list or dictionary whatever it is, it's working but is not checking for repetition among itself. so what i did is
for i in range(len(values)):
if ((newvalue not in values[i])):
values.append({newvalue: oldvalue})
但这不行。为什么?我如何解决这个问题?如果你有时间,请说明与字典有什么不同的列表,我在代码中有什么。一个列表或字典?
but this is not working. why? and how can i resolve this? and if you have time please explain how different is list with dictionary and what do i have in my code. a list or a dictionary?
谢谢
推荐答案
,如果你想要一个空的字典,不要做 values = []
,这将列出一个列表,而不是
first of all, if you want an empty dictionary, dont do values = []
that will make a list, instead do
values = {}
添加到字典时,
mydict[mykey] = myvalue
当检查是否有东西已经在钥匙这样做
when checking to see if something is already in the keys do this
if newkey not in mydict:
print('this will not overwrite anything')
我觉得你是误会字典的概念
当您这样做键
将是您的字典键,而 val
将是您的字典值。字典是{key:value}顺序的组合对,所以如果你执行 myDict [key]
,你将得到 value
I think you are misunderstanding the concept of a dictionary
When you do this key
will be your dictionary key, and val
will be your dictionary value. A dictionary is a combination of pairs of terms in the order {key: value} so if you do myDict[key]
you will get value
如果你想添加到字典,同时确保你没有覆盖任何东西,这个简单的例子将为你做这个。
If you want to add to a dictionary while making sure that you aren't overwriting anything, this simple example will do that for you.
if newkey not in mydict:
mydict[newkey] = newvalue
这篇关于消除python中字典中的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!