Working with unicode keys in a python dictionary

后端 未结 2 1229
孤街浪徒
孤街浪徒 2020-12-18 20:41

I am learning about the Twitter API using Python 2.7.x. I\'ve saved a number of random tweets and I am trying to process them. Each tweet is converted to a dictionary with j

2条回答
  •  执念已碎
    2020-12-18 21:18

    Python 2 handles translation between str and unicode keys transparently for you, provided the text can be encoded to ASCII:

    >>> d = {u'text': u'Foo'}
    >>> d.keys()
    [u'text']
    >>> 'text' in d
    True
    >>> u'text' in d
    True
    >>> d['text']
    u'Foo'
    >>> d[u'text']
    u'Foo'
    

    This means that if you get a KeyError for tweet['text'], then that dictionary has no such key.

提交回复
热议问题