我正在尝试创建一个新的 dict,它仅从另一个包含 50 个或更多字符的推文的 dict 中过滤值。我不知道用什么来添加到这个新的字典
我尝试使用 .update 但这似乎只是将 for 循环后的最后一条推文添加到新的 dict
def is_short_tweet(tweet):
if len(tweet) < 50:
return True
else:
return False
1_filtered = dict()
for i in 1_tweets:
if not is_short_tweet(i["text"]):
1_filtered.update(i) """ what do I use here to add to the new, filtered dict?"""
假设tweets
变量是一个字典列表,而不是一个字典。(根据您显示的代码,这对我来说没有意义)。
至于你说你要保持多鸣叫小号超过50个字符长,您可能需要使用列表字典。
def is_short_tweet(tweet):
if len(tweet) < 50:
return True
else:
return False
filtered = [] # define filtered as a list, instead of dictionary
for i in tweets:
if not is_short_tweet(i["text"]):
filtered.append(i) # use append() to add i (which is a dictionary ) to the list
关于.update()
字典方法的注意事项:
如果键不在字典中,则 update() 方法将元素添加到字典中。如果键在字典中,它会用新值更新键。
因此,由于您对每条推文都有相同的密钥,因此您所做的就是使用找到的最新长推文更新此信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句