【问题标题】:Python Dictionary with condition带条件的 Python 字典
【发布时间】:2020-04-10 19:54:51
【问题描述】:

在这两个条件下都存在此数据,但我的循环没有获取第二个字典的数据,它总是在第一个字典条件后终止。

在此处输入代码

if form and len(form) > 0:
    d1 = json.loads(form)
    d2 = list(d1.keys())
    v2 = list(d1.values())
    for x in range(len(d1)):
        if type(v2[x]) == dict and v2[x]['key']:
            selected_value = v2[x]['value']
            print("print 1")
        elif type(v2[x]) == dict and v2[x]['customer_id']:
             customer_names = v2[x]['customer_name']
             print("Print 2")

【问题讨论】:

  • 修正你的意图 - 如果type(v2[x]) == list,你怎么期望type(v2[x])也将成为dict
  • 您是说您的字典符合ifelif 语句的条件吗?因此您希望它同时打印您的print 语句?因为如果是这样,那不是if/elif/else 阻止works 的方式。如果您想/需要分别检查多个条件并为每个满足的条件做一些事情,您需要使用多个if 子句。
  • 您能否在d1 = json.loads(form) 之后添加print(d1) 并分享结果以便更好地理解
  • @Limbo -- 我只分享三行,因为数据量很大 - d1 : {'outlet': {'customer_id': '1238', 'customer_name': 'Nzmxzmm', ' field_type': 'autocomplete'}, 'coimbatore': {'key': '1', 'value': 'Demo', 'field_type': 'select'}} d1 : {'outlet': {'customer_id': '1100', 'customer_name': '测试值', 'field_type': 'autocomplete'}, 'coimbatore': {'key': '1', 'value': 'Demo', 'field_type': 'select' }}

标签: python python-3.x loops dictionary conditional-statements


【解决方案1】:

你让它变得比它必须的复杂得多:

d1 = {
     'outlet': {
         'customer_id': '1238',
         'customer_name': 'Nzmxzmm',
         'field_type': 'autocomplete'
     },
     'coimbatore': {
         'key': '1',
         'value': 'Demo',
         'field_type': 'select'
     }
 }

for item in d1.values():
    if isinstance(item, dict):
        if item.get("key"):
            selected_value = item['value']
            print("print 1")
        if item.get('customer_id'):
            customer_names = item['customer_name']
            print("Print 2")

请注意,这将(可能)在每次迭代时覆盖 selected_value 和/或 customer_names,因此您只会获得每个条件的最后一个值。此外,如果没有条目与其中一个条件匹配,您的 selected_value 和/或 customer_names 变量将不会被定义,因此在 for 循环之后尝试使用它们会引发错误。

【讨论】:

  • 你的方法看起来更通用谢谢!! @bruno desthuilliers
【解决方案2】:

几件事:

  1. 由于您正在检查type == dict,您可以在检查第二个条件之前将其添加为普通检查。
  2. 要检查该键是否存在于字典中,您可以使用if key in your_dictionary

在您的代码中实现上述两个,我们有这个:

    d1 = {'outlet': {'customer_id': '1238', 'customer_name': 'Nzmxzmm', 'field_type': 'autocomplete'}, 'coimbatore': {'key': '1', 'value': 'Demo', 'field_type': 'select'}}
    d2 = list(d1.keys())
    v2 = list(d1.values())
    for x in range(len(d1)):
       if type(v2[x]) == dict: # common typecheck condition
          if 'key' in v2[x]:
             selected_value = v2[x]['value']
             print(selected_value)
             print("print 1")
          elif 'customer_id' in v2[x]:
             customer_names = v2[x]['customer_name']
             print(customer_names)
             print("Print 2")

结果:

Demo
print 1
Nzmxzmm
Print 2

【讨论】:

  • "要检查字典中是否存在密钥,您可以使用 if key in your_dictionary.keys()" => 肯定不是。正确的方法是if key in dict,它是 O(1)(并且非常优化)。 dict.keys() 返回一个可迭代对象,所以 if key in dict.keys() 是 O(n)。此外,dicts 有一个 .get(key[, default=None]) 方法。
  • 而且由于您想提供“良好实践”建议(我完全支持,但必须正确完成,对吧?),推荐的类型检查方法是使用 isinstance(obj, cls) - 除非你真的想检查一个给定的类型,在这种情况下你想使用身份测试,即if type(obj) is cls
  • 最后,您可能想在the correct use of Python's for loop 上教授操作
  • 感谢@brunodesthuilliers 指出所有这些,我已经更新了我的答案以使用更优化的方式
猜你喜欢
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2015-12-21
  • 2014-09-02
  • 1970-01-01
  • 2018-06-30
相关资源
最近更新 更多