【问题标题】:To many print results - for key in dict对许多打印结果 - 输入 dict
【发布时间】:2021-02-25 14:03:06
【问题描述】:

大家早上好,

这里有许多与此相关的帖子,但是我是新手并且是一名动手学习者,因此当我不一定知道他们的最终目标时,很难掌握其他人编码提供的解决方案。这是我第一次尝试应用我的编码技能(或缺乏编码技能:D),但过去几个月我一直在研究 m1mo 并阅读/观看各种指南/教程。所以是的,我的代码对你们很多人来说可能看起来很愚蠢,但必须从某个地方开始!

目标:我想从 c_item_number_one 中的键的 product_dict 中提取字典值,此代码成功执行此操作,但如果该键执行 出现在字典中然后我想打印(“不在字典中”)

问题:虽然代码确实提供了基于键的字典值,但有时 c_item_number_one 不包含有效键。发生这种情况时,我想通过 print("Not in dictionary") 知道。目前,此代码将为未出现在我的 product_dict 中的每个字典条目打印“不在字典中”。如果它没有出现一次,我只希望它告诉我一次。

有时也会像这个例子一样,在字典中找到多个键,没关系。我希望它打印所有这些实例,因为我将添加进一步的验证当这发生在后面的代码中时。

请注意,以下是实际字典的一个小样本,实际上我有大约 1200 个条目,随着时间的推移还会添加更多条目。

“产品”只是我需要从描述中提取的十几个类别之一,因此这里的任何帮助都将极大地帮助我完成游戏,非常感谢!

product_dict = {
    'BEND': 'BEND',
    'FABRICATE SPOOL': 'PIPE SPOOL',
    'STUB-END': 'STUB END',
    'GSK': 'GASKET',
    'SA-106': 'PIPE',
    'PIPE': 'PIPE',
}

c_item_number_one = '12",PIPE , GR. B, SCH 40, WALL SMLS'

#Product for Item One
def item_one_product():
    found = True
    for key in product_dict:
        if key in c_item_number_one:
            item_number_one_product = product_dict[key]
            print(item_number_one_product)
        else:
            found = False
            print("Not in dictionary")

item_one_product()

打印出来:

Not in dictionary
Not in dictionary
Not in dictionary
Not in dictionary
PIPE
PIPE

【问题讨论】:

  • in 与字符串一起使用时要小心。例如,假设您的c_item_number 不包含PIPE,但它包含PIPERin 会高兴地回答是。
  • 最好的方法是用,分割字符串然后做in检查
  • c_item_number_one 是什么列表?您是否试图通过使用键作为列表c_item_number_one 的元素来查找字典中的值。如果存在密钥,则要打印该值。否则“不在字典中”?
  • @Epsi95 - 我也很担心这个问题,但是我计划通过提取与返回值相关的所有单词并删除不需要的单词来解决这个问题。拆分字符串似乎不起作用,因为我们有很多产品也以其他形式出现。一个例子是我们有法兰和法兰,管和管架等等。
  • @Akansha - c_item_number_one 最终将被输入,但目前只是一个整数,但不是一个列表。

标签: python dictionary for-loop


【解决方案1】:

你很接近,检查一下:

#Product for Item One
def item_one_product():
    not_found = True
    for key in product_dict:
        if key in c_item_number_one:
            item_number_one_product = product_dict[key]
            print(item_number_one_product)
            not_found = False
    if not_found:
        print("Not in dictionary")

item_one_product()

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 2013-04-03
    • 2020-06-24
    • 2015-07-17
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多