在Python中匹配列表和检测值变化之间的比较列表 [英] List of Dicts comparision to match between lists and detect value changes in Python

查看:372
本文介绍了在Python中匹配列表和检测值变化之间的比较列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从web服务调用返回的字典列表。

  listA = [{'name' :'foo','val':'x'},
{'name':'bar','val':'1'},
{'name':'alice' val':'2'}]



我需要比较上次调用服务的结果并拉出更改。所以在下次调用时我可以得到:

  listB = [{'name':'foo','val':' y'},
{'name':'bar','val':'1'},
{'name':'eve','val':'z'}] $ b

排序不保证,也不是列表的长度。名称不会改变。实际的数据有几个键,但我只关心'val'。



我试图找到一种方法来找回一个名字的列表

  changed = ['foo']#或[{'name':'foo'}] 


解决方案

我会建立一个辅助字典来存储 listA 的信息更明智:

  auxdict = dict((d ['name'],d ['val'])for listA)


b $ b

那么任务变得很容易:

  changed = [d ['name'] for d in listB 
if d ['name'] in auxdict and d ['val']!= auxdict [d ['name']]]

I have a list of dictionaries that I get back from a web service call,

listA = [{'name':'foo', 'val':'x'}, 
         {'name':'bar', 'val':'1'},
         {'name':'alice','val':'2'}]

I need to compare the results from the previous call to the service and pull out changes. So on the next call I may get:

listB = [{'name':'foo', 'val':'y'},
         {'name':'bar', 'val':'1'},
         {'name':'eve','val':'z'}]

The ordering is not guaranteed and nor is the length of list. The names won't change. The actual data has several more keys, but I'm only concerned with 'val'.

I am trying to find a way to get back a list of the names that have had their values change between calls only for the names that are in both lists.

changed = ['foo'] # or [{'name':'foo'}]

解决方案

I'd build an auxiliary dict to store listA's information more sensibly:

auxdict = dict((d['name'], d['val']) for d in listA)

then the task becomes very easy:

changed = [d['name'] for d in listB 
           if d['name'] in auxdict and d['val'] != auxdict[d['name']]]

这篇关于在Python中匹配列表和检测值变化之间的比较列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆