I need to create a dictionary like
d1={u'apple':True}
But I have "apple" in a string say str Problem is that if I write
>>> d1={}
>>> d[u'apple']=True
It works But if I write
>>> d1={}
>>> str="apple"
Then how to insert str in the unicode u added at the beginning?
2 Answers 2
In Python3 u'apple' and "apple" are the same. In Python2 both behave the same.
>>> "apple"==u"apple"
True
If you need to convert between byte strings and unicode strings, use decode:
"apple".decode('utf8')
2 Comments
.translate differs, etcYou could do this:
>>> d = {}
>>> str_ = "apple"
>>> d[str_.decode('ascii')] = True
>>> d
{u'apple': True}
But my question is why bother? Since in python 2.x, you have
"apple" == u"apple"
This means that dict lookups/insertions/deletes will all work the same whether you have the unicode object or the bytes object. So it doesn't really matter.
An analogy is using a dict key with the integer 0 or the float 0., it doesn't really make any difference which you use as the key.
u'...'produces an unicode object, but you don't need to use that syntax to convert a bytestring to a unicode object. You'd decode.