Reputation: 69
I have a dictionary
{u'value1': {u'Capacity1': 0, u'E1': 'None', u'status': u'ONLINE', u'name': u'value1', u'perf': 'None', u'Id': u'2005', u'id1': u'3000', u'Capacity2': 4}}
How do I remove the u' from both the key and the value (which itself is another dictionary?))
Thanks!
Upvotes: 6
Views: 11307
Reputation: 19733
u
denotes the unicode
representation.
you dont need to remove it or do something, just go for your code and do comparison
demo:
>>> type(u'b')
<type 'unicode'>
>>> u'b' == 'b'
True
Upvotes: 4
Reputation: 881675
One possibility might be (assuming Python 2):
def encode_dict(d, codec='utf8'):
ks = d.keys()
for k in ks:
val = d.pop(k)
if isinstance(val, unicode):
val = val.encode(codec)
elif isinstance(val, dict):
val = encode_dict(val, codec)
if isinstance(k, unicode):
k = k.encode(codec)
d[k] = val
return d
top_d = encode_dict(top_d)
You do need to remove (via .pop
) each Unicode key k
, then insert it back (with the newly encoded val
) after encoding k
into a byte string, otherwise (since, for keys made up only of ASCII characters, it is the case that k == k.encode('utf-8')
), the Unicode key would remain. Try that by using d.get
in lieu of d.pop
-- it doesn't do what you ask.
Whether you actually need what you ask is actually pretty dubious; if all the Unicode strings in d
(and embedded dicts therein) are made up only of ASCII characters, then d == encode_dict(d)
. However, the "stringified" forms would indeed look cosmetically different, and I guess that might be what you're after.
Upvotes: 5
Reputation: 5347
Since you want to compare,as others suggested you need not change it but if you need it.Here is it.
In [90]: d
Out[90]:
{u'value1': {u'Capacity1': 0,
u'Capacity2': 4,
u'E1': 'None',
u'Id': u'2005',
u'id1': u'3000',
u'name': u'value1',
u'perf': 'None',
u'status': u'ONLINE'}}
In [91]: c_k,c_v=d.keys(),d.values()
In [92]: z=[{str(k):str(v) for (k,v) in c_v[0].items()}]
In [93]: z1=[str(i) for i in c_k]
In [94]: dict(zip(z1,z))
Out[94]:
{'value1': {'Capacity1': '0',
'Capacity2': '4',
'E1': 'None',
'Id': '2005',
'id1': '3000',
'name': 'value1',
'perf': 'None',
'status': 'ONLINE'}}
Upvotes: 1
Reputation: 21
I had the same issue as I needed each dict item to be used in an SQL expression and the u' was getting in the way.
This is what worked for me:
for x,y in mylist.items():
mylist[x] = str(y)
Very simple :-)
Upvotes: 2