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

标签 python json parsing

我有 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/

相关文章:

parsing - 在 StandardTokenParsers 中使用正则表达式

python - 在 pandas 数据框中实现多个 if else 条件

json - 在 Swagger 中对 GeoJSON 建模

jquery - 为什么 JQuery 的 .post 没有返回数据?

c# - 为什么解析助手没有变得更易于使用?

java - XMLBeam 的默认值

python - 从python语法错误中的相对路径导入

Python 对象矩阵 - 定义属性

Python 数据包嗅探器

javascript - 防止从 Firebase 的 Angular 中的 JSON 中删除格式