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 to remove u 'from key and value (which in itself is another dictionary?))

Thanks!

+6
source share
4 answers

One possibility is possible (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 need to delete (via .pop ) each Unicode key k , and then insert it back (with the new coded val ) after encoding k into the byte string, otherwise (since for keys it consists only of ASCII characters, in this case k == k.encode('utf-8') ) the Unicode key will remain. Try this using d.get instead of d.pop - it does not do what you ask.

Do you really need what you ask is actually quite doubtful; if all Unicode strings in d (and embedded dicts in it) consist only of ASCII characters, then d == encode_dict(d) . However, “strict” forms would really look different in cosmetic terms, and I think this may be what you need.

+5
source

u stands for unicode representation.

you don’t need to delete it or do something, just go for your code and compare

demo:

 >>> type(u'b') <type 'unicode'> >>> u'b' == 'b' True 
+4
source

I had the same problem as in every dict element that was used in the SQL expression and u 'was in the way.

This is what worked for me:

  for x,y in mylist.items(): mylist[x] = str(y) 

Very simple: -)

+1
source

Since you want to compare, like others, you do not need to change it, but if you need it. Here it is.

 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'}} 
0
source

Source: https://habr.com/ru/post/980845/


All Articles