gpt4 book ai didi

python - 我需要使用 python json 解析将我的 2 个列表合并为另一个列表

转载 作者:行者123 更新时间:2023-12-01 06:26:26 29 4
gpt4 key购买 nike

我有 2 个 json 文件:房间.json学生.json我需要通过 Students.json 中的房间 ID 和属性房间将它们组合到另一个列表中rooms.json:

[
{
"id": 0,
"name": "Room #0"
},
{
"id": 1,
"name": "Room #1"
},
{
"id": 2,
"name": "Room #2"
}
]

学生.json:

[
{
"id": 0,
"name": "Ryan Keller",
"room": 1
},
{
"id": 1,
"name": "Brooke Ferrell",
"room": 1
},
{
"id": 2,
"name": "Travis Tran",
"room": 0
}
]

我正在使用这个:

import json

rooms_file = 'rooms.json'
with open(rooms_file) as f:
rooms_new = json.load(f)
students_file = 'students.json'
with open(students_file) as file:
student_new = json.load(file)

relocation_file = 'relocation.json'


for i in students_file:
if "room" == id in rooms_file:
with open(relocation_file) as fl:
relocation_new = json.dump(relocation_file,'w')

我做错了什么,请帮忙。它什么也不返回,但可能应该创建一个文件“relocation.json”其中包含这样的列表:

 [
{
"id": 0,
"name": "Room #0"
"name": "Travis Tran",
},
{
"id": 1,
"name": "Room #1"
"name": "Brooke Ferrell",
"name": "Ryan Keller",
},

]

最佳答案

您可以尝试下面的代码吗,我认为您期望的答案不应该具有相同的键名称,因此我已将其重命名为 student_name 作为键(如果需要,您可以更改 nameroom_name)。我希望这对您来说也应该没问题。

import json

with open('files/rooms.json') as f:
room_list = json.load(f)

with open('files/students.json') as file:
student_list = json.load(file)


relocation_list = []

for student_dict in student_list:
for room_dict in room_list:
new_dict = {}
if student_dict['room'] == room_dict['id']:
new_dict["student_name"] = student_dict['name']
new_dict.update(room_dict)
relocation_list.append(new_dict)

with open('relocation.json', 'w') as f:
f.write(str(relocation_list))

print(relocation_list)

输出:

[{'student_name': 'Ryan Keller', 'id': 2, 'name': 'Room #2'}, {'student_name': 'Brooke Ferrell', 'id': 1, 'name': 'Room #1'}, {'student_name': 'Travis Tran', 'id': 0, 'name': 'Room #0'}]

采用列出综合方式:

import json

with open('files/rooms.json') as f:
room_list = json.load(f)

with open('files/students.json') as file:
student_list = json.load(file)

print([{**room_dict, "student_name": student_dict['name']} for room_dict in room_list for student_dict in student_list if student_dict['room'] == room_dict['id']])
# output
# [{'id': 0, 'name': 'Room #0', 'student_name': 'Travis Tran'}, {'id': 1, 'name': 'Room #1', 'student_name': 'Brooke Ferrell'}, {'id': 2, 'name': 'Room #2', 'student_name': 'Ryan Keller'}]
<小时/>

编辑对于评论中提到的新要求

  • 避免 relocation_list 中出现重复的 ID - 此处我们将 student_name 的值合并到学生列表
  • 按值对字典列表进行排序 - 引用:检查此 link还有很多其他方法
import json

with open('files/rooms.json') as f:
room_list = json.load(f)

with open('files/students.json') as file:
student_list = json.load(file)


relocation_list = []


# We arent considering about duplicate item as it is created by same loop
def check_room_id_in_relocation_list(id_to_check):
is_exist, index, item = False, None, {}
for index, item in enumerate(relocation_list):
if id_to_check == item['id']:
is_exist, index, item = True, index, item
return is_exist, index, item


for student_dict in student_list:
for room_dict in room_list:
new_dict = {}
if student_dict['room'] == room_dict['id']:
is_room_exist, index, item = check_room_id_in_relocation_list(room_dict['id'])
if is_room_exist:
# To merge same ids
# since it already exist so update list's item with new student_name
# instead of new key we are assigning list of names to key "student_name" to
relocation_list[index]['student_name'] = [relocation_list[index]['student_name'], 'new nameeeee']
else:
new_dict["student_name"] = student_dict['name']
new_dict.update(room_dict)
relocation_list.append(new_dict)

print("student list:", student_list)
print("room list: ", room_list)
print("relocation_list:", sorted(relocation_list, key=lambda k: k['id']))
with open('relocation.json', 'w') as f:
f.write(str(sorted(relocation_list, key=lambda k: k['id'])))

# output
# student list: [{'id': 0, 'name': 'Ryan Keller', 'room': 2}, {'id': 1, 'name': 'Brooke Ferrell', 'room': 1}, {'id': 2, 'name': 'Travis Tran', 'room': 0}, {'id': 3, 'name': 'New User', 'room': 2}]
# room list: [{'id': 0, 'name': 'Room #0'}, {'id': 1, 'name': 'Room #1'}, {'id': 2, 'name': 'Room #2'}]
# relocation_list: [{'student_name': ['Travis Tran', 'new nameeeee'], 'id': 0, 'name': 'Room #0'}, {'student_name': 'Brooke Ferrell', 'id': 1, 'name': 'Room #1'}, {'student_name': 'Ryan Keller', 'id': 2, 'name': 'Room #2'}]

关于python - 我需要使用 python json 解析将我的 2 个列表合并为另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119112/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com