Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove u' (unicode) from a dictionary in Python?

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!

like image 424
user3738426 Avatar asked Jan 11 '15 22:01

user3738426


3 Answers

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.

like image 160
Alex Martelli Avatar answered Nov 01 '22 13:11

Alex Martelli


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
like image 38
Hackaholic Avatar answered Nov 01 '22 14:11

Hackaholic


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 :-)

like image 30
Duke Avatar answered Nov 01 '22 13:11

Duke