python变量revenue怎么定义_在Python中,如何检查另一个dict中值的键值(在一个dict中定义)?...

Given a mapping dict mapping:

{

'John': 'A',

'Mary': 'B',

'Tim' :'C'

}

I am then provided a dict spend:

{

'John': 23,

'Mary': 1,

}

and a dict revenue:

{

'A': 12,

'B': 2,

'C': 23

}

then:

for k, v in spend.items():

# do stuff

Within this loop, I want to check if an entry in revenue does not have a corresponding entry in spend (based on our mapping). One such example is Tim (because 'C' is present in revenue, but 'Tim' is not present in spend).

An approach of looping again (within this for loop) - this time over revenue.keys() and checking that the key is not in spend.keys() - unfortunately is not an option as this will result in len(revenue) number of duplicates, per match.

How do we achieve the desired reverse checking without a loop?

解决方案

You can do this easily if you reverse your keys and values in the mapping dictionary and then loop over revenue dicitonary. You do not need to permanently reverse it, just reverse it and store in a new dictionary before you do the loop.

Example -

reversedmapping = {v:k for k,v in mapping.items()}

for k,v in revenue.items():

if (k not in reversedmapping) or (reversedmapping[k] not in spend):

print(k)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值