匹配词典列表最有效的方法是什么?

2024-10-06 10:24:55 发布

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

我有一个这样的字典列表:

lst = [{'City or Community': 'Augusta', 'State':'GA', 'Parent Company': 'WoW!'},
      {'City or Community': 'Augusta', 'State':'GA', 'Parent Company': 'Comcast'}]

迭代列表以查找城市/州组合具有多个结果的实例的最有效方法是什么?你知道吗

这就是我现在要做的:

def search(complete):
    #searching through the full list for footprints which overlap by city, county, state, etc
    trial = []
    for y in complete:
        for x in complete:
            for subdicts in y:
                for otherdicts in x:
                    if otherdicts['Parent Company'] != subdicts['Parent Company'] and (otherdicts['City or Community'], otherdicts['State']) == (subdicts['City or Community'], subdicts['State']):

Tags: orincommunitycity列表for字典company
3条回答

以下是defaultdict的一种方法:

from collections import defaultdict

combined = defaultdict(list)
lst = [{'City or Community': 'Augusta', 'State':'GA', 'Parent Company': 'WoW!'},
       {'City or Community': 'Augusta', 'State':'GA', 'Parent Company': 'Comcast'},]

# Loop through your list of dictionaries and
# create a combined dictionary where keys are cities and states, and values are lists of companies
for d in lst:
    combined[(d['City or Community'], d['State'])].append(d['Parent Company'])

# For each of the keys in the combined dictionary, only print them out
# if there are more than one companies for that key
print(list(cityAndState for (cityAndState, companies) in combined.items() if len(companies) > 1))
>>> [('Augusta', 'GA')]
[x for x, y in itertools.groupby(lst, lambda x: (x['City or Community'], x['State'])) if sum(1 for z in y) > 1]
# => [('Augusta', 'GA')]

试试collections.Counter()

import collections

lst = [{'City or Community': 'Augusta', 'State':'GA', 'Parent Company': 'WoW!'},
  {'City or Community': 'Augusta', 'State':'GA', 'Parent Company': 'Comcast'}]

cntr = collections.Counter(
          [ (d['City or Community'], d['State']) for d in lst ]
       )

相关问题 更多 >