将python中的字典拆分为键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4019639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:52:36  来源:igfitidea点击:

splitting a dictionary in python into keys and values

pythonlistdictionary

提问by Fergus Barker

How can I take a dictionary and split it into two lists, one of keys, one of values. For example take:

我怎样才能把一本字典分成两个列表,一个键,一个值。举个例子:

{'name': 'Han Solo', 'firstname': 'Han', 'lastname': 'Solo', 'age': 37, 'score': 100, 'yrclass': 10}

and split it into:

并将其拆分为:

['name', 'firstname', 'lastname', 'age', 'score', 'yrclass']
# and
['Han Solo', 'Han', 'Solo', 36, 100, 10]

Any ideas guys?

有什么想法吗?

采纳答案by Wolph

Not that hard, try help(dict)in a console for more info :)

没那么难,请help(dict)在控制台中尝试以获取更多信息:)

keys = dictionary.keys()
values = dictionary.values()

For both keys and values:

对于键和值:

items = dictionary.items()

Which can be used to split them as well:

也可用于拆分它们:

keys, values = zip(*dictionary.items())

Note 0The order of all of these is consistent within the same dictionary instance. The order of dictionaries in Python versions below 3.6 is arbitrary but constant for an instance. Since Python 3.6 the order depends on the insertion order.

注 0所有这些的顺序在同一个字典实例中是一致的。低于 3.6 的 Python 版本中的字典顺序是任意的,但对于实例来说是恒定的。从 Python 3.6 开始,顺序取决于插入顺序。

Note 1In Python 2 these all return a list()of results. For Python 3 you need to manually convert them if needed: list(dictionary.keys())

注 1在 Python 2 中,这些都返回一个list()结果。对于 Python 3,您需要根据需要手动转换它们:list(dictionary.keys())