简体   繁体   English

从列表字典中过滤元素

[英]Filter elements from dictionary of lists

I have a dictionary named graph (directed graph), inside it has people and its friendships, giving a weight of this friendships. 我有一本名为graph(有向图)的字典,里面有人和它的友情,给人以这种友情的分量。 I'd like to remove a specific person inside this dict or change the weight of this friendship. 我想在此字典中删除特定的人,或更改这种友谊的重要性。 Inside the dictionary I have sets of frozensets. 在字典中,我有一组Frozensets。 The dictionary looks something like this: 字典看起来像这样:

graph={'Name1': [('Name2', 1),('Name3',3),('Name8',2)], 'Name5': [('Name1',2), ('Name3',5)], 'Name2':[('Name3',1),('Name5',4)]}

I would like to remove a specific friend of a specific person. 我想删除特定人的特定朋友。 For example, I'd like to remove 'Name8' from the friendships of 'Name1', resulting in this new dictionary: 例如,我想从“ Name1”的友情中删除“ Name8”,从而得到这个新字典:

graph={'Name1': [('Name2', 1),('Name3',3)], 'Name5': [('Name1',2), ('Name3',5)], 'Name2':[('Name3',1),('Name5',4)]}

Another issue is to change a weight of a friendship. 另一个问题是改变友谊的分量。 For example, changing the weight of 'Name5' friendship with 'Name3' to 2, resulting in something like this: 例如,将“ Name5”和“ Name3”的权重更改为2,结果如下:

graph={'Name1': [('Name2', 1),('Name3',3),('Name8',2)], 'Name5': [('Name1',2), ('Name3',2)], 'Name2':[('Name3',1),('Name5',4)]}

For the first issue, one way would be by filtering the 'Name1' key value from the dictionary, and merging the other keys with the dictionary unpacking operator (more on this usage here ): 对于第一个问题,一种方法是通过过滤字典中的'Name1'键值,然后将其他键与字典拆包运算符合并(有关此用法的更多信息,在此处 ):

{**graph, **{'Name1':[(i,j) for i,j in graph['Name1'] if i != 'Name8']}}

{'Name1': [('Name2', 1), ('Name3', 3)],
 'Name5': [('Name1', 2), ('Name3', 5)],
 'Name2': [('Name3', 1), ('Name5', 4)]}

And for the second, similarly you could do: 第二,类似地,您可以执行以下操作:

{**graph, **{'Name5':[(i,j) if i != 'Name3' else (i,2) for i,j in graph['Name5']]}}

{'Name1': [('Name2', 1), ('Name3', 3), ('Name8', 2)],
 'Name5': [('Name1', 2), ('Name3', 2)],
 'Name2': [('Name3', 1), ('Name5', 4)]}

General solution for filtering with multiple conditions: 多种条件过滤的通用解决方案:

from collections import defaultdict

d = defaultdict(list)
for k,v in graph.items():
    if k == 'Name1':
        for i,j in v:
            if i != 'Name8':
                d[k].append((i,j))
    elif k == 'Name5':
        for i,j in v:
            if i != 'Name3':
                d[k].append((i,2))     
            else:
                d[k].append((i,j))     
    else:
        d[k].append(v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM