私信  •  关注

Ani M

Ani M 最近创建的主题
Ani M 最近回复了
3 年前
回复了 Ani M 创建的主题 » 比较python中字典列表中的值

以下代码应该可以工作:

def resultHandler(extractedResult):
  jsonList = []
  for i in range(len(extractedResult) // 2):
    jsonList.append({"Id": i})
  for i in range(len(extractedResult)):
    for j in range(len(jsonList)):
      if jsonList[j]["Id"] == extractedResult[i]["Id"]:
        if "title" in extractedResult[i]:
          jsonList[j]["title"] = extractedResult[i]["title"];
        else:
          jsonList[j]["location"] = extractedResult[i]["location"];
  return jsonList;

extractedResult = [{"Id": 0, "title":"example1"}, {"Id": 1, "title":"example2"}, {"Id": 0, "location":"example3"}, {"Id": 1, "location":"example4"}]

jsonList = resultHandler(extractedResult)

print(jsonList)

输出:

[{'Id': 0, 'title': 'example1', 'location': 'example3'}, {'Id': 1, 'title': 'example2', 'location': 'example4'}]

此代码首先填充 jsonList Id值从0到长度的一半 extractedResult (ID的数量也是如此)。

然后,对于每一本字典 提取结果 ,我们在字典里找到了 jsonList 和匹配的ID。如果 提取结果 包含一个密钥, "title" ,然后我们在 jsonList .这同样适用于 "location" .

我希望这有助于回答你的问题!如果您需要任何进一步的澄清或详细信息,请告诉我:)

3 年前
回复了 Ani M 创建的主题 » Python将对象列表添加为dict值

你可以使用 .append() 功能:

message = {'message': 'bla bla bla', 'data':[]}
my_list = [('a', 1), ('b', 2)]

for item in my_list:
  message['data'].append({'text': item[0], 'value': item[1]})

print(message)

输出:

{'message': 'bla bla bla', 'data': [{'text': 'a', 'value': 1}, {'text': 'b', 'value': 2}]}

这将附加字典,因为索引处的元素尚未定义。