我正在尝试减去dict1 - dict2.无论结果是否为负数,我只想学习这个概念:)
owner = ['Bob', 'Sarah', 'Ann']
dict1 = {'Bob': {'shepherd': [4,6,3],'collie': [23, 3, 45], 'poodle':[2,0,6]}, {'Sarah': {'shepherd': [1,2,3],'collie': [3, 31, 4], 'poodle': [21,5,6]},{'Ann': {'shepherd': [4,6,3],'collie': [23, 3, 45], 'poodle': [2,10,8]}}
dict2 = {'Bob': {'shepherd': 10,'collie': 15,'poodle': 34},'Sarah': {'shepherd': 3,'collie': 25,'poodle': 4},'Ann': {'shepherd': 2,'collie': 1,'poodle': 0}}我要:
wanted = dict1 = {'Bob': {'shepherd': [-6,-4,-7],'collie': [8, -12, 30], 'poodle':[-32,-34,-28]}, {'Sarah': {'shepherd': [-2,-1,0],'collie': [-22, 6, -21], 'poodle': [17,1,2]},{'Ann': {'shepherd': [2,4,1],'collie': [22, 2, 44], 'poodle': [2,10,8]}}我仍然是字典的新手,所以这里是我一直在尝试的,但是得到了NoneType错误。我认为这是因为dict1比dict2具有更多的值,但我无法找到执行上述计算的方法。
wanted = {}
for i in owner:
wanted.update({i: dict1.get(i) - dict2.get(i)})发布于 2016-08-23 04:18:02
您可以使用嵌套字典理解。我稍微修改了一下你的字典,因为它的语法不正确(还有一些额外的大括号)。不需要所有者数组,因为我们可以只使用字典中的键。
dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
dict2 = {
'Bob': {'shepherd': 10, 'collie': 15, 'poodle': 34},
'Sarah': {'shepherd': 3, 'collie': 25, 'poodle': 4},
'Ann': {'shepherd': 2, 'collie': 1, 'poodle': 0},
}
wanted = {
owner: {
dog: [num - dict2[owner][dog] for num in num_list]
for dog, num_list in dog_dict.iteritems()
} for owner, dog_dict in dict1.iteritems()
}
print wanted输出:
{
'Sarah': {
'shepherd': [-2, -1, 0],
'collie': [-22, 6, -21],
'poodle': [17, 1, 2]
},
'Bob': {
'shepherd': [-6, -4, -7],
'collie': [8, -12, 30],
'poodle': [-32, -34, -28]
},
'Ann': {
'shepherd': [2, 4, 1],
'collie': [22, 2, 44],
'poodle': [2, 10, 8]
}
}这是假定dict2具有与dict1相同的所有密钥。如果不是这样,则需要设置一些默认值以避免使用KeyError。
编辑:以下是如何为不熟悉词典的人解释字典理解的简要说明。如果你对列表理解比较满意,那么字典的理解是非常相似的,只是你创建了一本字典而不是一张列表。所以,{i: str(i) for i in xrange(10)}会给你一本{0: '0', 1: '1', ..., 9: '9'}字典。
现在我们可以把它应用到解决方案上了。此代码:
wanted = {
owner: {
dog: [num - dict2[owner][dog] for num in num_list]
for dog, num_list in dog_dict.iteritems()
} for owner, dog_dict in dict1.iteritems()
}相当于:
wanted = {}
for owner, dog_dict in dict1.iteritems():
wanted[owner] = {}
for dog, num_list in dog_dict.iteritems():
wanted[owner][dog] = [num - dict2[owner][dog] for num in num_list]https://stackoverflow.com/questions/39092224
复制相似问题