Working with unicode keys in a python dictionary

后端 未结 2 1227
孤街浪徒
孤街浪徒 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.

    0 讨论(0)
  • 2020-12-18 21:30
    Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> d = {u'text': u'Foo'}
    >>> print "d:{text}".format(**d)
    d:Foo
    
    0 讨论(0)
提交回复
热议问题