Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

python - Filtering Dictionary with List of Lists as Value

I have a dictionary with values being a list of lists, e.g.:

Review_dict["0002"]

[['0002', '0292', '4', datetime.datetime(1998, 2, 27, 11, 1, 34)],
 ['0002', '0251', '5', datetime.datetime(1998, 2, 27, 12, 2, 24)],
 ['0002', '0050', '5', datetime.datetime(1998, 2, 27, 12, 3, 24)],
 ['0002', '0314', '1', datetime.datetime(1998, 3, 4, 10, 5, 45)]]

I want to remove certain list (within the "big" list), where 2nd element = '0251' or '0314'.

e.g. Review_dict["0002"] should become:

[['0002', '0292', '4', datetime.datetime(1998, 2, 27, 11, 1, 34)],
 ['0002', '0050', '5', datetime.datetime(1998, 2, 27, 12, 3, 24)]]

I have come up with this code but I want to know if there's a simpler/ more elegant way to do so.

remove = ['0251', '0314']

for key in list(Review_dict):
    for ID in remove:
        for num in range(len(Review_dict[key])):
            if Review_dict[key][num][1] == ID:
                del Review_dict[key][num]
question from:https://stackoverflow.com/questions/66060741/filtering-dictionary-with-list-of-lists-as-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could just mutate the values of your outer dict:

remove = ['0251', '0314']

for v in Review_dict.values():
    v[:] = (lst for lst in v if lst[1] not in remove)

Generally, one should not repeatedly remove from a list as each remove has linear complexity. Building from scratch is the better option. Whether this performs better depends on your data and how much there actually is to remove.

As a mutation, the slice assignment v[:] = ... allows to ignore the keys of the outer dict entirely as you don't need to rebind them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...