【问题标题】:How to check if a key in a dictionary startswith the a key in another dictionary?如何检查字典中的键是否以另一个字典中的键开头?
【发布时间】:2014-04-05 21:54:32
【问题描述】:

这是我正在尝试做的简化方案。我有两个字典:

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

【问题讨论】:

  • 您的代码似乎完全符合您的要求。 dictB 中没有以c 开头的键;因此chocolate3 不应该被找到,它不是。你的实际问题是什么?
  • @inspectorG4dget,我认为它应该使用另一个循环来打印它找不到的那些。

标签: python dictionary key startswith


【解决方案1】:

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

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(...)

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

【讨论】:

  • 嗨 gribbler,这个问题的扩展。如果我想在上述情况下“打印 itemA + itemB”而不是“打印 itemA + str(dictA[itemA])”,我该怎么做?当我尝试相应地修改您的建议时,我收到“itemB is not defined”。
  • @user3502285,您需要将第一个循环改回原来的形式。我认为在第二个循环中打印任何 itemB 没有意义
【解决方案2】:

我会跟踪你找到的键,并输出你最后没有找到的键:

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

for key_b in dictB.keys():
  for key_a in dictA.keys():
    if key_a.startswith(key_b):
      print "I can find: %s %s" % (key_a, dictA[key_a])
      found_keys.add(key_a)
      break
print "I couldn't find: %s" % dict((k, dictA[k]) for k in set(dictA.keys()) - found_keys)

输出:

I can find: apple 1
I can find: orange 2
I can find: mango 4
I couldn't find: {'chocolate': 3}

编辑:我刚刚看到gnibbleranswer。我比我更喜欢它,虽然由于我的不使用 any 并显式调用 dict 对象的 keys() 方法,它可能更容易理解(但是,再次,如果你明白 gnibbler 的答案是,就用那个)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多