将python中的字典拆分为键和值 [英] splitting a dictionary in python into keys and values

查看:74
本文介绍了将python中的字典拆分为键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取字典并将其分为两个列表,一个是键,一个是值.例如:

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}

并将其拆分为:

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

有什么想法的人吗?

推荐答案

不难,请在控制台中尝试 help(dict)了解更多信息:)

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

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

对于键和值:

items = dictionary.items()

也可以用来拆分它们:

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

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

Note 0 The 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.

注释1 在Python 2中,所有这些都返回结果的 list().对于Python 3,您需要根据需要手动将其转换: list(dictionary.keys())

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

这篇关于将python中的字典拆分为键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆