[英]How can I return key value dictionary pairs from a list of dictionaries of unknown amount?
I have data that is either being returned as a single dictionary, example:我有作为单个字典返回的数据,例如:
{'key': 'RIDE', '3': 27.3531}
or as a list of dictionaries of unknown amount (ie. could be up to 20 dictionary lists or 2 as shown), example:或作为未知数量的字典列表(即最多可以是 20 个字典列表或 2 个,如图所示),例如:
[{'key': 'GH', '3': 154.24}, {'key': 'RIDE', '3': 27.34}]
I'd like to write a piece of code that will iterate through the list of dictionaries and return all the key value pairs within each dictionary.我想编写一段代码来遍历字典列表并返回每个字典中的所有键值对。
Any help would be appreciated, thank you!任何帮助将不胜感激,谢谢!
To experiment with this we first have to write some code with a dummy data provider that either returns a dictionary or a list of dictionaries:为了对此进行试验,我们首先必须使用一个返回字典或字典列表的虚拟数据提供程序编写一些代码:
import random
def doSomething():
if random.random() <= 0.5:
return {'key': 'RIDE', '3': 27.3531}
else:
return [{'key': 'GH', '3': 154.24}, {'key': 'RIDE', '3': 27.34}]
#
Now we encounter exact this situation you described: That you sometimes receive a dictionary, sometimes a list of dictionaries.现在我们遇到了您所描述的这种情况:您有时会收到一本字典,有时会收到一个字典列表。
Now: How to deal with this situation?现在:如何处理这种情况? It's not too difficult:这不是太难:
x = doSomething()
if isinstance(x, dict):
x = [ x ]
for item in x:
print(item)
So as we know we either receive a single dictionary or alternatively a list of dictionaries we can test of which type the value returned is.因此,正如我们所知,我们要么接收一个字典,要么接收一个字典列表,我们可以测试返回的值是哪种类型。 As it is much more convenient to always process a list the above example first converts the returned dictionary into a list before any additional data processing takes place.由于总是处理列表要方便得多,所以上面的示例首先将返回的字典转换为列表,然后再进行任何其他数据处理。
So this is done by "correcting an error": The error is here that your data provider does not always return data of the same type.所以这是通过“纠正错误”来完成的:错误在于您的数据提供者并不总是返回相同类型的数据。 So whenever we receive a dictionary we first pack the dictionary into a list.因此,每当我们收到一本字典时,我们首先将字典打包到一个列表中。 Only after then we begin with the data processing we want to in the first place.只有在那之后,我们才开始我们首先想要的数据处理。 Here this processing is to just print the dictionary, but of course you can iterate through the keys and values as well as you mentioned or do any kind of data processing you might feel appropriate.在这里,这个处理只是打印字典,但当然你可以像你提到的那样遍历键和值,或者做任何你认为合适的数据处理。
But: It is not a good idea to have some kind of function or subsystem of any kind that returns different types of data.但是:拥有某种类型的 function 或返回不同类型数据的任何类型的子系统不是一个好主意。 As you see this enforces to implement extra logic on the caller's side.如您所见,这强制在调用方实现额外的逻辑。 Additionally it complicates things if we want to write a specification (and we WANT to write a specification in/for more complex programs.)此外,如果我们想编写规范,它会使事情复杂化(并且我们想为更复杂的程序编写规范。)
Example:例子:
import typing
import random
def doSomething() -> typing.Union[dict,typing.List[dict]]:
if random.random() <= 0.5:
return {'key': 'RIDE', '3': 27.3531}
else:
return [{'key': 'GH', '3': 154.24}, {'key': 'RIDE', '3': 27.34}]
#
Here the specification is a formal one using the capabilities of typing
.这里的规范是使用typing
能力的正式规范。 So this information about the returned type is specified in a formal way.因此,有关返回类型的信息以正式的方式指定。 Though this information is typically not evaluated by Python directly under normal circumstances this specification provides any programmer with the knowledge about returned types.尽管在正常情况下 Python 通常不会直接评估此信息,但此规范为任何程序员提供了有关返回类型的知识。
Of course we could have written such a specification in a non-formal way by writing some kind of text document as well, but that does not make any difference: In general having different types of return values complicates things unnecessarily.当然,我们也可以通过编写某种文本文档以非正式的方式编写这样的规范,但这没有任何区别:通常,具有不同类型的返回值会使事情变得不必要地复杂化。 You can do that - there are situations where this makes sense - but in general it's better to avoid that situation as best as you can to simplify things.你可以这样做——在某些情况下这是有道理的——但总的来说,最好尽可能避免这种情况,以简化事情。
For example using this approach:例如使用这种方法:
import random
def doSomething() -> typing.List[dict]:
# the old code we might choose not to change for some reason ...
if random.random() <= 0.5:
x = {'key': 'RIDE', '3': 27.3531}
else:
x = [{'key': 'GH', '3': 154.24}, {'key': 'RIDE', '3': 27.34}]
# but we can compensate ...
if isinstance(x, dict):
x = [ x ]
return x
#
Now we made the function to always return data of the same type.现在我们使 function 始终返回相同类型的数据。 Which is now much more convenient for us: As a) it simplifies processing for the caller and b) simplifies learning about the data returned in the first place.现在对我们来说更方便了:a)它简化了调用者的处理过程,b)首先简化了对返回数据的学习。
So having converted everything to return only data of a single type our main routine will simplify to this:因此,将所有内容转换为仅返回单一类型的数据后,我们的主程序将简化为:
for item in x:
print(item)
Or if you want to display keys and values:或者,如果您想显示键和值:
for item in x:
for k, v in item.items():
print(k, "->", v)
Or whatever kind of data processing you have in mind with the data returned.或者您对返回的数据进行任何类型的数据处理。
Remember as a rule of thumb, in any kind of scripting or programming language:作为经验法则,请记住,在任何类型的脚本或编程语言中:
Always provide data in a way that it is easy for the caller to use and that the whole logic is easy to understand for the programmer.始终以调用者易于使用且整个逻辑易于程序员理解的方式提供数据。 Make providing data in good a way a problem for the subroutine, not the caller.使提供数据成为子程序的问题,而不是调用者的问题。 Simplify the caller's life as much as possible.尽可能简化调用者的生活。
(Yes, you can decide to violate this principle and not follow it but if you do that then you really must have a very good reason. Then you really need to know what you're doing as then you have a very very special situation. Let me tell you from my 25 years of experience as a professional software developer: In 99.999% of all cases you will not have such a special situation. And I have the feeling that your situation does not fall into this category of such a special situation;-) ) (是的,你可以决定违反这个原则而不遵循它,但如果你这样做了,那么你真的必须有一个很好的理由。然后你真的需要知道你在做什么,因为你有一个非常非常特殊的情况。用我25年的专业软件开发经验告诉你:在99.999%的情况下,你不会有这种特殊情况。而且我感觉你的情况不属于这种特殊情况。 ;-) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.