python - 如何检查字典中的键是否以另一个字典中的键开头?

标签 python dictionary key startswith

这是我正在尝试做的事情的简化场景。我有两个字典:

dictA = {"apple": 1, "orange": 2, "chocolate": 3, "mango": 4}
dictB = {"man": "abc", "or": "asdf", "app": "fasdfkl"}

如何让它打印(三个键+值的实际顺序无关紧要):

I can find...
orange2
mango4
apple1

I cannot find...
chocolate3

我曾尝试做类似的事情,但卡在了第二部分。

print "I can find ..."
for itemA in dictA:
    for itemB in dictB:
        if itemA.startswith(itemB):
            print itemA + str(dictA[itemA])

它会打印

I can find ...
orange2
mango4
apple1

最佳答案

首先将第一个循环简化为此

print "I can find ..."
for itemA in dictA:
    if any(itemA.startswith(itemB) for itemB in dictB):
        print itemA + str(dictA[itemA])

第二个循环将使用 if not any(...)

这不是一个非常有效的算法,但我猜你只是在做一个练习

关于python - 如何检查字典中的键是否以另一个字典中的键开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887341/

相关文章:

python - 在 Python 中保存和加载大型字典的最快方法

android - 如何仅在我的 Android 应用中静音按下音量键的声音?

asp.net - 使用没有 API key 的谷歌地图?

java - 如何将反引号放在名为 key for hibernate 的列名中

python - 如何在Python中使用多重处理生成大型语料库的tfdf?

python - 在 django 中提供多对多相关模型的模型知识

delphi - 通用字典类是否有通过索引获取键的方法?

javascript - 相当于字典的数据结构?

python - RQ worker 抛出 "ValueError"

python - 如何检查NCCL的版本