如果 dict 包含某个键,如何从另一个列表中的值向列表中的 dict 添加键?
我有一个字典列表。这些字典要么只包含一个键('review'),要么包含两个键('review' 和 'response')。当字典包含键“响应”时,我想添加两个键,其中包含来自两个列表的值。
data = [{'response': 'This is a response',
'review': 'This is a review'},
{'review': 'This is only a review'},
{'response': 'This is also a response',
'review': 'This is also a review'}]
date = ['4 days ago',
'3 days ago']
responder = ['Manager',
'Customer service']
Run Code Online (Sandbox Code Playgroud)
我尝试了以下操作,但由于对于包含关键“响应”的每个字典,我只想从每个列表的值中添加 1,因此我不确定如何执行此操作。
for d in data:
if 'response' in d:
for i in date:
d['date'] = i
for i in responder:
d['responder'] = i
Run Code Online (Sandbox Code Playgroud)
输出显示它当然只添加列表的最后一个值,因为我正在遍历列表。我怎样才能解决这个问题?
[{'date': '3 days ago', …Run Code Online (Sandbox Code Playgroud) 如何按单词的位置分割字符串?
我的数据如下所示:
test = 'annamarypeterson, Guest Relations Manager, responded to this reviewResponded 1 week agoDear LoreLoreLore,Greetings from Amsterdam!We have received your wonderful comments and wanted to thank you for sharing your positive experience with us. We are so thankful that you have selected the Andaz Amsterdam for your special all-girls weekend getaway. Please come and see us again in the near future and let our team pamper you and your girlfriends!!Thanks again!Anna MaryAndaz Amsterdam -Guest RelationsReport response as inappropriateThank you. …Run Code Online (Sandbox Code Playgroud) 我有多个 (400) json 文件,其中包含一个目录中的 dict,我想读取这些文件并将其附加到列表中。我试过像这样循环遍历目录中的所有文件:
path_to_jsonfiles = 'TripAdvisorHotels'
alldicts = []
for file in os.listdir(path_to_jsonfiles):
with open(file,'r') as fi:
dict = json.load(fi)
alldicts.append(dict)
Run Code Online (Sandbox Code Playgroud)
我不断收到以下错误:
FileNotFoundError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)
但是,当我查看目录中的文件时,它为我提供了所有正确的文件。
for file in os.listdir(path_to_jsonfiles):
print(file)
Run Code Online (Sandbox Code Playgroud)
只需使用文件名打开其中之一也可以。
with open('AWEO-q_GiWls5-O-PzbM.json','r') as fi:
data = json.load(fi)
Run Code Online (Sandbox Code Playgroud)
在循环中是不是出错了?
我有一个浮动列表,看起来像这样:
predictions_dec = [13.0, 8.6, 4.9, -1.5, 6.2, 7.7, 2.0, 10.0, 7.7, 12.7,...]
Run Code Online (Sandbox Code Playgroud)
我想清理这些数据,方法是给出高于10.0的数字10.0和低于0.0的数字(所以所有负数)为0.0.我正在使用以下if语句执行此操作:
predictions_clean = []
for pred in predictions_dec:
if pred >= 10:
predictions_clean.append(10.0)
if pred <= 0:
predictions_clean.append(0.0)
else:
predictions_clean.append(pred)
Run Code Online (Sandbox Code Playgroud)
这段代码似乎有效,但有趣的是:
len(predictions_dec)
1222
len(predictions_clean)
1816
Run Code Online (Sandbox Code Playgroud)
我对if语句的理解并不是那么好.在if语句中,我做错了什么?