简体   繁体   中英

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. 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. 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:

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:

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 ):

{**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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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