Skip to main content
 首页 » 编程设计

python之浏览字典列表并仅选择存在键的行

2025年05月04日13虾米姐

如何搜索字典列表并仅选择存在特定键(无论值如何)的行?例如,在这三行中,我只想保留存在 "userid" 的行(最后两行)。

[{'long': None, 'tweetid': None, 'timestamp': None, 'lat': None}, 
 {'userid': '113503286', 'long': '-87.624387', 'tweetid': '595084326489956352', 'timestamp': '1430714134224', 'lat': '41.852653'},  
 {'userid': '2421024865', 'long': '-87.629798', 'tweetid': '595084376632729600', 'timestamp': '1430714146179', 'lat': '41.878114'}] 

我试过下面的代码,但是我得到一个错误:

datum = [ row for row in data if row['tweet_time'] in row] 
Traceback (most recent call last): 
File "<pyshell#102>", line 1, in <module> 
datum = [ row for row in data if ['tweet_time'] in row] 

请您参考如下方法:

[row for row in data if row['tweet_time'] in row] 

没有。但几乎。 dict 的包含检查检查键是否存在。

[row for row in data if 'userid' in row]