所以我有两个字典,每个字典都有如下方式的键值对:
firstDict = {
'HImJYsulal': 0
'psNnxwFVmv': 0
'4B0IaN1P5x': 0
'MxZzGOlefq': 0
}
我想用我的代码实现以下目标:
循环查看第一个和第二个字典。如果第一个字典的值在第二个字典中,则将restaurant_key(在firstDict中)的int值增加1
做同样的事情,除了主for循环是secondDict,内部循环是firstDict(这是有原因的)。将餐厅键(secondDict的)的int值增加1
代码运行了,但是我得到的不是我想要的,而是:
^{pr2}$这不是我想要的。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])
事先非常感谢。在
如果两个字典中都有键,则两个字典中的int值递增1
演示:
代码问题:
仅当
k==k2
时才需要递增。所以每当代码进入else loop
时,当这个条件为false时,在其他情况下,我们将值递增1。在只需在if循环中增加值。在
尝试1:
^{pr2}$尝试2:
您不需要执行嵌套迭代来执行所述操作:
关键是要注意你的两个操作都是在dicts有共同点的键上操作的,即交叉点。然后您可以使用内置的
set
数据类型,与嵌套循环相比,它的速度将惊人地快,更不用说您的意图会更清楚:-)相关问题 更多 >
编程相关推荐