python如何比较两个字典_用Python方式比较两个字典列表中的值

I'm new to Python and am still trying to tear myself away from C++ coding techniques while in Python, so please forgive me if this is a trivial question. I can't seem to find the most Pythonic way of doing this.

I have two lists of dicts. The individual dicts in both lists may contain nested dicts. (It's actually some Yelp data, if you're curious.) The first list of dicts contains entries like this:

{business_id': 'JwUE5GmEO-sH1FuwJgKBlQ',

'categories': ['Restaurants'],

'type': 'business'

...}

The second list of dicts contains entries like this:

{'business_id': 'vcNAWiLM4dR7D2nwwJ7nCA',

'date': '2010-03-22',

'review_id': 'RF6UnRTtG7tWMcrO2GEoAg',

'stars': 2,

'text': "This is a basic review",

...}

What I would like to do is extract all the entries in the second list that match specific categories in the first list. For example, if I'm interested in restaurants, I only want the entires in the second list where the business_id matches the business_id in the first list and the word Restaurants appears in the list of values for categories.

If I had these two lists as tables in SQL, I'd do a join on the business_id attribute then just a simple filter to get the rows I want (where Restaurants IN categories, or something similar).

These two lists are extremely large, so I'm running into both efficiency and memory space issues. Before I go and shove all of this into a SQL database, can anyone give me some pointers? I've messed around with Pandas some, so I do have some limited experience with that. I was having trouble with the merge process.

解决方案

Suppose your lists are called l1 and l2:

All elements from l1:

[each for each in l1]

All elements from l1 with the Restaurant category:

[each for each in l1

if 'Restaurants' in each['categories']]

All elements from l2 matching id with elements from l1 with the Restaurant category:

[x for each in l1 for x in l2

if 'Restaurants' in each['categories']

and x['business_id'] == each['business_id'] ]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值