所以我有两个字典,每个字典都有以下方式的键值对:
firstDict = {
'HImJYsulal': 0
'psNnxwFVmv': 0
'4B0IaN1P5x': 0
'MxZzGOlefq': 0
}
我想用我的代码实现的目标如下:
循环遍历第一个和第二个字典。如果第一个字典的值在第二个字典中,则将restaurant_key的int值(在firstDict中)增加1
做同样的事情,除了主要的for循环是secondDict而内部循环是firstDict(其中有一个原因)。 restaurant_key(of secondDict)的int值增加1
代码运行全部,但我没有得到我想要的东西,我得到了:
(u'HImJYsulal', 0)
(u'jXDXpoeuWY', 1)
(u'ctNyMKpCoE', 2)
(u'vWsFNwTnz1', 3)
(u'0zcfI67S6X', 4)
(u'aGjUr2Ittw', 5)
(u'eQ5rGvpoRs', 6)
(u'6Q96oO26ua', 7)
...and so on and so forth
这不是我想要的。 int值应该有所不同。理想情况下它看起来应该是这样的:
(u'HImJYsulal', 4)
(u'jXDXpoeuWY', 0)
(u'ctNyMKpCoE', 1)
(u'vWsFNwTnz1', 5)
(u'0zcfI67S6X', 2)
以下是代码:
import read_spins
firstDict = {}
# initialSpots
read_spins.read_json('initialSpots.json', firstDict)
#for obj in firstDict:
#print(obj,firstDict[obj])
#chosenSpots
secondDict = {}
read_spins.read_json('chosenSpots.json', secondDict)
#for all merchants in the initial spot
for k, v in firstDict.iteritems():
#for all merchants in the chosen spot
for k2, v2 in secondDict.iteritems():
#if the merchant appears in the initial spot, and also in the chosen spot,
#end the loop and go to the next one. We're only interested in those that aren't in the chosen spot.
#This means that they were dropped.
if k == k2:
print("broke with: " + k)
break
else:
#the merchant isn't in the chosen spots,so therefore the merchant was dropped.
firstDict[k] = firstDict[k] + 1
#for all merchants in the chosen spot
for k, v in secondDict.iteritems():
#for all merchants in the initial spot
for k2, v2 in firstDict.iteritems():
#if the merchant appears in the chosen spot, but also in the initial spot,
#end the loop and go to the next merchant. THis means the merchant was
#originally selected.
if k == k2:
print("broke with: " + k)
break
else:
#the merchant isn't in the initial spot, thus the merchant was added.
secondDict[k] = secondDict[k] + 1
for obj in firstDict:
print(obj, firstDict[obj])
print(" ")
print("CHOSEN SPOTS")
print("++++++++++++")
print(" ")
for obj in secondDict:
print(obj, secondDict[obj])
非常感谢您提前。
答案 0 :(得分:1)
如果密钥互相存在,则将两个字典中的int值增加1
<强>演示强>:
>>> a = {"a": 1, "b":2, "c":0}
>>> b = {"d": 1, "b":2, "c":0}
>>> ab = set(b.keys()).intersection(set(a.keys()))
>>> ab
set(['c', 'b'])
>>> for i in ab:
... a[i] = a[i] + 1
... b[i] = b[i] + 1
...
>>> a
{'a': 1, 'c': 1, 'b': 3}
>>> b
{'c': 1, 'b': 3, 'd': 1}
您的代码问题:
只有在k==k2
时才需要增加。因此,当此条件为false时,每次代码进入else loop
时,否则我们将值递增1。
只需在if循环中增加值。
尝试1 :
for k, v in secondDict.iteritems():
increment = False
for k2, v2 in firstDict.iteritems():
if k == k2:
secondDict[k] = secondDict[k] + 1
print("broke with: " + k)
break
尝试2 :
for k, v in secondDict.iteritems():
if k in firstDict:
secondDict[k] = secondDict[k] + 1
答案 1 :(得分:1)
您不需要执行嵌套迭代来执行您所声明的操作:
for key in set(firstDict.keys()) & set(secondDict.keys()):
firstDict[key] += 1
secondDict[key] += 1
关键是要注意你的两个操作都是在dicts共有的键上操作的,即交叉点。然后你可以使用内置的set
数据类型,与嵌套循环相比,速度会非常快 - 更不用说你的意图会更清晰: - )