python-搜索字典子列表;将字典键转换为值

标签 python search dictionary sublist

假设我有以下字典(我正在使用的字典大得多):

dict1={1:["item", "word", "thing"], 2:["word", "item"], 3:["thing", "item", "item"]}

并将字典中使用的每个单词都存储在一个列表中:

all_words=["item", "word", "thing"]

我想通过字典子列表运行列表中的每个单词,并返回找到它们的所有子列表的键,将它们存储在元组中。所以我想得到:

dict2={"item":(1, 2, 3), "word":(1, 2), "thing":(1, 3)}

这是我所拥有的:

dict2={}    
for word in all_words:
    for key, sublist in dict2.items():
        for word in sublist:
            if word not in sublist:
                dict2[word]=dict2[word]+key
            else:
                dict2[word]=key

最佳答案

因此,基于评论,您的固定程序将如下所示

>>> dict2 = {}
>>> for word in all_words:
...     # Iterate over the dict1's items
...     for key, sublist in dict1.items():
...         # If the word is found in the sublist
...         if word in sublist:
...             # If the current word is found in dict2's keys
...             if word in dict2:
...                 # Append the current key as a one element tuple
...                 dict2[word] += (key,)
...             else:
...                 # Create a one element tuple and assign it to the word
...                 dict2[word] = (key,)
... 
>>> dict2
{'item': (1, 2, 3), 'word': (1, 2), 'thing': (1, 3)}

如果你了解字典理解,那么同样可以写成

>>> {word: tuple(k for k, v in dict1.items() if word in v) for word in all_words}
{'item': (1, 2, 3), 'word': (1, 2), 'thing': (1, 3)}

整个元组创建逻辑,基于每个对应的dict1,已被压缩为一个生成器表达式,并转换为一个包含tuple的元组(k for k, v in dict1.items() if word in v)

关于python-搜索字典子列表;将字典键转换为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098655/

相关文章:

python - 段落的标题大小写

python - 强制从 URL 下载图像的最长时间

elasticsearch - 如何在搜索时对 Elasticsearch 中的字段执行数学运算?

python - 使用 Tweepy 通过 API 1.1 搜索推文

python - Python字典中的整型键是否按优先级排序和排序?

python - 字符串中的重复字符

python - 如何更改 Pandas DataFrame 面积图上的年份间隔?

python - 改进 Django 搜索

arrays - 为什么在 swift 中无法在数组中添加 json 键值

python - 如何检测字典中的任何元素是否发生变化?