Reputation:
I have Unicode :-
x = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]] <type 'unicode'>
print type(x)
<type 'unicode'>
I need to convert this as a list of tuples like [('customer', '=', 1),('parent_id', '=', False)]
Please help me
Upvotes: 0
Views: 878
Reputation: 30268
Python 2:
>>> x = u"[[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]"
>>> type(x)
<type 'unicode'>
>>> y=[tuple(t) for t in eval(x)]
>>> y
[(u'customer', u'=', 1), (u'parent_id', u'=', False), (u'user_id', u'=', 1059)]
>>> type(y)
<type 'list'>
>>> type(y[0])
<type 'tuple'>
>>>
>>> map(lambda t: tuple(t),eval(x))
[(u'customer', u'=', 1), (u'parent_id', u'=', False), (u'user_id', u'=', 1059)]
>>>
Python 3:
>>> x = u"[[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]"
>>> type(x)
<class 'str'>
>>> [tuple(t) for t in eval(x)]
[('customer', '=', 1), ('parent_id', '=', False), ('user_id', '=', 1059)]
>>>
Upvotes: 0
Reputation: 2108
>>> x = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]
>>> y = map(lambda t: tuple(t),x)
>>> y
[(u'customer', u'=', 1), (u'parent_id', u'=', False), (u'user_id', u'=', 1059)]
Upvotes: 0
Reputation: 6495
I guess you mean:
>>> x = u"[[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]"
>>> print type(x)
<type 'unicode'>
You can use eval(x)
to translate x
to a list
.
>>> l = eval(x)
>>> print type(l)
<type 'list'>
Upvotes: 0
Reputation: 15204
Does this work for you?
my_uni_list = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]]
result = [tuple(x) for x in my_uni_list]
Upvotes: 2
Reputation: 5950
Just iterate
if you are using python 3.x and use tuple()
>>> L = [[u'customer', u'=', 1], [u'parent_id', u'=', False], [u'user_id', u'=', 1059]] <type 'unicode'>
>>> [tuple(i) for i in L]
[('customer', '=', 1), ('parent_id', '=', False), ('user_id', '=', 1059)]
Upvotes: 1