简体   繁体   English

Python:如何动态遍历dict对象?

[英]Python: How to iterate over a dict object dynamically?

I want to write so data to a file, but the data can vary depending on its source. 我想将数据写入文件,但是数据可能会根据其来源而有所不同。

At the moment my code just does the following: 目前,我的代码仅执行以下操作:

try:
    file.write('{value1}'.format(value1=data["value1"]))
except:
    pass

try:
    file.write('{value2}'.format(value2=data["value2"]))
except:
    pass

#...

Due to the nature of the input data, these value keys may or may not be present, hence why I'm doing the above so when I get a KeyError I can just ignore it. 由于输入数据的性质,这些值键可能存在也可能不存在,因此为什么要执行上述操作,所以当我收到KeyError时,可以忽略它。

So my question is, is there a better way of doing the above? 所以我的问题是,有没有更好的方法来做上述事情? A more 'pythonic' way rather than this pretty wet solution? 还有一种更“ pythonic”的方式,而不是这种非常潮湿的解决方案?

example_input1: example_input1:

'{"value1": 1.0, "value2": 1.2}'

example_input2: example_input2:

'{"value2": 1.5}'

I guess ultimately I should standardise the input data, but unfortunately this is coming from a third-party API so isn't really an option. 我想最终我应该对输入数据进行标准化,但是不幸的是,这是来自第三方API,因此实际上不是一种选择。

Yes, you can simply use: 是的,您可以简单地使用:

for key in ('value1','value2'):
    if key in data:
        file.write('{}'.format(data[key]))

So here if key in data first checks if there is a key in the dictionary (eg 'value1' ). 因此,这里if key in data首先检查字典中是否存在键(例如'value1' )。 Given that is the case, we use file.write('{}'.format(data[key])) to write the corresponding value to the file. 在这种情况下,我们使用file.write('{}'.format(data[key]))将相应的值写入文件。

The advantage of using a for loop is furthermore that you can easily add and remove keys you want to print from the file. 使用for循环的优点还在于,您可以轻松地从文件中添加和删除要打印的键。

If on the other hand you wish to write all keys that are in the dictionary, you can iterate over the dictionary : 另一方面,如果您希望write字典中的所有键 ,则可以遍历字典

for val in data.values():
    file.write('{}'.format(val))

Mind however that the order of the key/values in a dictionary is not necessary the insertion order. 然而记住,在一个字典中的键/值的顺序不是必需的插入顺序。 So the values can be shuffled. 因此,可以将这些值改组。

You can use json library to convert your input string into dictionary-like object. 您可以使用json库将输入的字符串转换为类似字典的对象。

>>> import json
>>> input1 = '{"value1": 1.0, "value2": 1.2}'
>>> input2 = '{"value2": 1.5}'
>>> input1 = json.loads(input1)
>>> input2 = json.loads(input2)
>>> for key in input1.keys():
...  print(input1[key])
... 
1.2
1.0
>>> for key in input2.keys():
...  print(input2[key])
... 
1.5

If the order is not important in your case, you can just loop over your data like below: 如果顺序对您而言不重要,则可以如下循环显示数据:

for v in data.values():
    file.write('{}'.format(v))

Output: 输出:

>>> data = {"value1": 1.0, "value2": 1.2}
>>> for v in data.values():
...     print(v)
...
1.2
1.0
>>>

It depends, but I think you don't want to write all data you got, but only some one if they exists . 这要看情况,但是我想您不想写所有得到的数据, 如果有的话就只写一些。

So here is a pythonic way ( try / except ): 所以这是一种pythonic方式( try / except ):

inputs = [
    {"value1": "foo", "value2": "bar"},
    {"value1": "foo"},
    {"value3": "baz", 'unexpected': '??'}
]

expected_keys = ['value1', 'value2', 'value3']

for data in inputs:
    for key in expected_keys:
        try:
            file.write(data[key])
        except KeyError:
            pass

inputs is just a list of dict used as example, expected_keys is a list of keys you want to write if they exists in inputs. inputs只是作为示例使用的dict列表, expected_keys是要在输入中存在的键列表。

With that you never miss an existing key and never raise KeyError if a key is missing. 这样一来,您就不会错过现有的密钥,并且如果缺少密钥,也不会引发KeyError

This is the real pythonic way to handle this, see Python's EAFP 这是处理此问题的真正pythonic方式,请参阅Python的EAFP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM