打印一个空字典

0 投票
3 回答
1261 浏览
提问于 2025-04-17 20:32

我正在尝试使用Twitter的接口,但有些推文返回的是空的,比如说标签(hashtags)。我该怎么打印出来呢?或者至少显示一条消息,告诉我它是空的。

这是我目前的代码:

def get_tweets(q, count=100, result_type="recent"):
    result = search_tweets(q, count, result_type)
    following = set(t.friends.ids(screen_name=TWITTER_HANDLE)["ids"])
    for tweet in result['statuses']:
        try:
            print tweet
            print tweet['text']
            print str(tweet['user']['id'])
            print tweet['hashtags']
            #print 'user mentions ' + tweet['users_mentions'] + tweet['hashtags']
            time.sleep(30) # Sleep for 1 hour
        except TwitterHTTPError as e:
            print "error: ", e
            if "blocked" not in str(e).lower():
                quit()      

但是我在

print tweet['hashtags']

这里遇到了一个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in get_tweets
KeyError: 'hashtags'

3 个回答

2

使用 get 方法,第一个参数是你要查找的键,第二个参数是如果这个键不存在时要返回的值:

print tweet.get('hashtags', None)
3

正如之前所说的,你可以使用 dict.get() 这个方法来查找数据。否则,你也可以使用下面的 if-else 结构:

if 'hashtags' in tweet:
    print tweet['hashtags']
else:
    print "No hashtags"
3

dict.get()

你可以使用 get() 这个函数。

根据 Python 文档 的说明:

get(key[, default]): 如果字典中有这个 key,就返回它对应的值;如果没有,就返回 default。 如果没有提供 default,默认返回 None,这样这个方法就不会抛出 KeyError 错误。

一个例子

In [2]: foo = {'a': 1}

In [3]: foo['b']
...
KeyError: 'b'

In [4]: foo.get('b', "B not found")
Out[4]: 'B not found'

检查键是否存在

另外,你也可以先检查这个键是否存在,然后再决定是否报告错误。

if 'hashtags' in tweet.keys():
    #do stuff if the hashtag exists
else:
    #do error condition

你可以根据自己的情况选择最合适的方法。

你的代码

下面是你代码在做了这些修改后可能的样子。

def get_tweets(q, count=100, result_type="recent"):
    ...
    for tweet in result['statuses']:
        ...
        print tweet.get('hashtags', "")
        if 'user_mentions' in tweet.keys():
            print 'user mentions ' + 
                tweet.get['users_mentions'] +  
                tweet.get('hashtags', '')

撰写回答