确保dict列表中的每个键都有一个带有key的dict

2024-06-13 13:11:38 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文: 我使用Ajax调用从python模块返回一些复杂的JSON。我必须使用一个键列表,并确认一个单项dict列表包含一个带有每个键的dict。你知道吗

示例:

mylist=['this', 'that', 'these', 'those']

mydictlist=[{'this':1},{'that':2},{'these':3}]

我怎么知道mydictlist缺少“那些”键?一旦我知道了这一点,我就可以将{thats':4}附加到mylist中。简单地检查“那些”是行不通的,因为列表是动态的。数据结构无法更改。你知道吗

谢谢。你知道吗


Tags: 模块json示例数据结构列表that动态ajax
3条回答

pandas包是处理dicts问题列表的好方法。它接受所有键并使它们成为列标题,具有相似键的值填充同一列。你知道吗

看看这个:

import pandas as pd

mydictlist=[{'this':1},{'that':2},{'these':3}]

# Convert data to a DataFrame
df = pd.DataFrame(mydictlist)

# List all the column header names and check if any of the key words are missing
df.columns

最直接的方法是遍历容器并检查:

for key in mylist:
    if not any(key in dic for dic in mydictlist):
        print key, "missing"

但是,如果您有很多键和/或字典,这将是不高效的:对于mylist中的每个元素,它在mydictlist上迭代一次,即O(n*m)。相反,考虑一个集合操作:

print set(mylist).difference(*mydictlist)

简单的代码是将搜索列表转换为一个集合,然后使用差异来确定缺少的内容:

missing = set(mylist).difference(*mydictlist)

这就得到了missing{'those'}。你知道吗

由于命名的set方法可以接受多个参数(它们本身不必是set),因此您只需将所有的dict解压为difference的参数,就可以一次从所需键的set中减去它们。你知道吗

如果确实需要处理重复项(为了确保在mydictlist的键中至少多次看到keys中的每个keys,因此mylist可能包含一个值,该值必须在dict中出现两次),可以使用collectionsitertools来获取剩余计数:

from collections import Counter
from itertools import chain

c = Counter(mylist)
c.subtract(chain.from_iterable(mydictlist))
# In 3.3+, easiest way to remove 0/negative counts
c = +c

# In pre-3.3 Python, change c = +c to get the same effect slightly less efficiently
c += Counter()

相关问题 更多 >