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!
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.
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
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With