简体   繁体   English

如何将元组转换成字典?

[英]How to Convert Tuple to Dictionary?

i'm using Python 2.5 and Win XP. 我正在使用Python 2.5和Win XP。 i have a tuple as below: 我有一个元组如下:

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>> 

i want to convert tuple a[1] to dictionary because i want to use the key and value. 我想将元组a [1]转换为字典,因为我想使用键和值。 pls help to advise. 请帮助提供建议。 tq q

>>> import ast
>>> ast.literal_eval(a[1])
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}

First split the string on comma. 首先用逗号分割字符串。 Iterate over all parts. 遍历所有部分。 Split each part on colon. 在结肠上分割每个部分。 Convert the strings into integers. 将字符串转换为整数。 Add the second integer as value for the first integer as key. 将第二个整数作为值添加到第一个整数作为键。

If you trust the source of a[1] you can use eval : 如果您相信a[1]的来源,则可以使用eval

dictionary = eval(a[1])

Otherwise you can use json (or simplejson in Python 2.5: see here ) : 否则,您可以使用json (或Python 2.5中的simplejson请参见此处 ):

import json
dictionay = json.loads(a[1])

Note : it mostly depends on how you got the string: if it comes from a repr and cannot be hacked, eval may be good. 注意 :这主要取决于您如何获取字符串:如果它来自repr并且无法被黑客入侵,则eval可能会很好。 If it came from json.dumps (which would result in a different string), you should use json.loads . 如果它来自json.dumps (这将导致不同的字符串),则应使用json.loads

There is another way to do it, without using any imports. 还有另一种方法,不使用任何导入。

A simple list comprehension (temp): 一个简单的列表理解 (临时):

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>> temp = [[int(c) for c in b.split(":")] for b in a[1].strip('{}').split(",")]
>>> a_dict = dict(temp)
>>> a_dict[1]
2
>>> a_dict[2]
4

The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. dict()构造函数直接从存储为元组的键值对列表中构建字典。 When the pairs form a pattern, list comprehensions can compactly specify the key-value list. 当这些对形成一个模式时,列表推导可以紧凑地指定键值列表。

dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127} dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension {2: 4, 4: 16, 6: 36} dict([('sape',4139),('guido',4127),('jack',4098)]){'sape':4139,'jack':4098,'guido':4127} dict([ (2,4,6)中的x的(x,x ** 2)])#使用列表理解{2:4,4:16,6:36}

Copy & Paste from: http://docs.python.org/tutorial/datastructures.html 复制并粘贴来自: http : //docs.python.org/tutorial/datastructures.html

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

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