python字典dragonloot_dict中的值不会让我改变它(Value in dict won't let me change it)

dict中的值不会让我改变它(Value in dict won't let me change it)

我正在尝试编写一个更新字典中值的程序。

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

#stuff = addToInventory(stuff, dragonLoot)

for i in range(len(dragonLoot)):

for k, v in stuff.items():

if dragonLoot[i] == k:

v += 1

displayInventory(stuff)

正如您所看到的,我已经在我的主要部分移动了片段,以确保它不是该功能的问题。 外部for循环也有效。 问题是, v不会得到更新。 displayInventory()打印与顶部声明中相同的值。

提前感谢您的意见!

I am trying to write a program which updates values in a dictionary.

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

#stuff = addToInventory(stuff, dragonLoot)

for i in range(len(dragonLoot)):

for k, v in stuff.items():

if dragonLoot[i] == k:

v += 1

displayInventory(stuff)

As you can see I already moved the snippet in my main to ensure that it's not a problem with the function. The outer for-loop also works. The problem is, v just dosen't get updated. displayInventory() prints the same values as in the declaration at the top.

Thank you in advance for your input!

原文:https://stackoverflow.com/questions/32601540

更新时间:2020-02-19 23:00

最满意答案

您可以使用以下方法:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

for item in dragonLoot:

stuff[item] = stuff.get(item, 0) + 1

print stuff

给你:

{'gold coin': 45, 'dagger': 2, 'torch': 6, 'rope': 1, 'arrow': 12, 'ruby': 1}

stuff.get(item, 0)返回字典中的项,但如果它不存在(例如ruby ),则返回默认值0 。 我在一个值上添加一个并将其分配回字典。

You can use the following approach:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

for item in dragonLoot:

stuff[item] = stuff.get(item, 0) + 1

print stuff

Giving you:

{'gold coin': 45, 'dagger': 2, 'torch': 6, 'rope': 1, 'arrow': 12, 'ruby': 1}

stuff.get(item, 0) returns item from the dictionary, but if it is not present (such as ruby) it returns the default value of 0. I than add one to the value and assign it back to the dictionary.

2015-09-16

相关问答

它没有得到相同的dict 。 它是制作原始dict的浅表副本,并且==按值而不是按身份进行比较,因为它具有所有相同的键和值,它们是相等的,即使它不是相同的 dict 。 如果你测试了print b._store is a ,你会得到False ,因为它is测试对象的身份。 至于你的其他问题,我不是100%确定你要去那里,但是我认为你反对的是你没有从继承dict受益,因为你仍然有一个存储所有的属性你的价值观。 那只是因为你没有在这里正确地进行继承。 您必须委派父类的方法,而不是创建自己的_store

...

有很多方法可以做到这一点,但实质上,你想要比较你的dict中每一对可能的键。 最简单的方法是不重新发明轮子并使用itertools: import itertools

for k1, k2 in itertools.combinations(image_dict_copy, 2):

if hamming_distance(image_dict_copy[k1], image_dict_copy[k2]) > .85:

duplicates.append((k1, k2))

...

最终, json不支持序列化任意python对象。 如果你想这样做,你可以看看pickle 。 或者,您可以在Ball上创建一个替代构造函数,它将使用dict值对其进行初始化: class Ball(object):

@classmethod

def from_json(self, dictionary):

b = cls()

b.__dict__.update(dictionary)

return b

...

假设可以

...

您的错误是因为您的MyDict变量最初将整数映射到字符串。 当您尝试更新它时,您将该值视为一个set,当它是一个字符串时。 你可以使用defaultdict : combined_dict = defaultdict(set)

# first add all the values from MyDict

for key, value in MyDict.iteritems():

combined_dict[int(key)].add(value)

# then add the valu

...

你可以使用词典理解: >>> dict1 = {'project' : 'Non-Work Time', 'cost' : 'N/A'}

>>> dict2 = {'Administration': 'F99' , 'Non-Work Time': 'Q99'}

>>> dict1 = {i:dict2[dict1['project']] if i=='cost' and j=='N/A' else j for i,j in dict1.items()}

>>> dict1

{'project':

...

感谢Brian ,我发现了解决方案。 我应该使用came_from[pos]=previous 。 Thanks to Brian, I discovered the solution. I should use came_from[pos]=previous.

当你附加dictionary ,你实际上是附加它的引用,因为字典是可变的 - 这就是为什么所有条目实际上都指向字典的单个副本。 使用它的复制方法来附加它的副本而不是原始的: b.append(dictionary.copy())

When you are appending dictionary, you are actually appending its reference since dictionaries are mutable - that's why all of the entr

...

您可以使用以下方法: stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

for item in dragonLoot:

stuff[item] = stuff.get(item, 0) + 1

print stuff

给你: {'gol

...

这个你需要reduce() ...... attrmap = {

"new_key_1": ('subdict1', 'subdict2', 'old_key_1'),

...

}

print reduce(lambda x, y: x[y], attrmap[somekey], old_object)

You're going to need reduce() for this one... attrmap = {

"new_key_1": ('subdict1', 'subd

...

只创建了一个子字典。 你现在拥有的是字典本身可以通过多种方式访问。 dict[0.5]和dict[1]引用相同的字典(而不是它的副本)。 实现你想要做的事情的一种方法是使用字典理解: dict1 = {k_outer: {k_inner:0 for k_inner in m} for k_outer in k}

这为每个键创建了一个新的嵌套dict,从而避免了它们都访问相同嵌套dict的问题。 Only one sub-dictionary was ever created. What you

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值