【问题标题】:i need to unit my 2 lists to another 1 using python json parsing我需要使用 python json 解析将我的 2 个列表单元到另一个 1
【发布时间】:2020-02-07 18:25:54
【问题描述】:

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

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

students.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",
  },

]

【问题讨论】:

  • 您的输出似乎与您尝试做的不匹配。 Ryan Keller 在顶部的房间值为 2,但在输出中位于房间 1。这是想要的吗?请清理您的输出文件或更清楚您想要的逻辑。
  • 对不起,现在好像需要这样

标签: python json parsing


【解决方案1】:

你能试试下面的代码吗?我认为你期望的答案不应该有相同的键名,所以我把它重命名为student_name作为键(如果需要,你可以将name更改为room_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'}]

编辑 对于 cmets 中提到的新需求

  • 避免 relocation_list 中的重复 ID - 我们将 student_name 的值合并到学生列表中
  • 按值排序dict列表-参考:检查此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'}]

【讨论】:

  • 我试过了,它输出如下: [{'id': 5, 'name': 'Room #5', 'student_name': 'Cassandra Wilson'}, {'id': 5 , 'name': 'Room #5', 'student_name': 'Cassandra Wilson'},
  • 我需要为 10000 名学生和 1000 个房间做这个,但现在我正在尝试 10 个学生和 10 个房间,尝试更简单 Ur 代码很好,谢谢你的帮助,但它不是这样我希望)
  • 很抱歉,您现在可以检查一下吗?我已经更正了代码。
  • 谢谢你,你帮了我这么多,我可以请你帮我把它按房间 id 从 1 到 10 排序,你可能知道例如离开房间的学生3 在一本字典中,例如 [{'student_name': 'Ryan Keller', 'student_name': 'Brooke Ferrell','id': 0, 'name': 'Room #0'}
  • 当然,所以您的第一个要求是希望最终结果(relocation_list) 按room 数字排序?第二部分我完全不明白,你能用另一个例子再解释一下,以便我现在可以快速尝试吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 2017-08-27
  • 2013-12-09
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多