Reputation: 99
i'm using Python 2.5 and 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. pls help to advise. tq
Upvotes: 1
Views: 2110
Reputation: 11049
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
Upvotes: 1
Reputation: 17606
If you trust the source of a[1]
you can use eval
:
dictionary = eval(a[1])
Otherwise you can use json
(or simplejson
in Python 2.5: see here) :
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.
If it came from json.dumps
(which would result in a different string), you should use json.loads
.
Upvotes: 1
Reputation: 414159
>>> import ast
>>> ast.literal_eval(a[1])
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}
Upvotes: 5
Reputation: 6142
The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. 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}
Copy & Paste from: http://docs.python.org/tutorial/datastructures.html
Upvotes: 0
Reputation: 15136
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.
Upvotes: 3