如果存在多个值,则从defaultdict提取值

2024-05-23 23:35:40 发布

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

我得到了一个名为“anagrams”的默认字典,看起来像这样:

defaultdict(set,
            {'a': {'a'},
             'act': {'act', 'cat', 'tac'},
             'hitw': {'with'},
             'acn': {'can'},
             'eikl': {'like'},
             'ehty': {'they'},
             'eilnst': {'listen', 'silent'},
             'or': {'or'},
             'be': {'be'}})

现在,如果有多个值分配给一个键,我只想列出这些值。我一直在网上搜索一个(列表)理解,可以做到这一点,但我运气不好

结果应该是:

[{'act', 'cat', 'tac'}, {'listen', 'silent'}]

有人能给个提示吗


Tags: or字典withbeactcanlistencat
1条回答
网友
1楼 · 发布于 2024-05-23 23:35:40
>>> d = {'a': {'a'},
...              'act': {'act', 'cat', 'tac'},
...              'hitw': {'with'},
...              'acn': {'can'},
...              'eikl': {'like'},
...              'ehty': {'they'},
...              'eilnst': {'listen', 'silent'},
...              'or': {'or'},
...              'be': {'be'}}
>>>
>>> [v for v in d.values() if len(v) > 1]
[{'act', 'cat', 'tac'}, {'listen', 'silent'}]

相关问题 更多 >