мне нужно объединить мои 2 списка в другой 1, используя python json разбор - PullRequest
1 голос
/ 07 февраля 2020

У меня есть 2 json файлы: комнаты. json студенты. json Мне нужно объединить их в другой список по идентификатору комнаты и комнате атрибутов в студентах. json комнаты. 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')

Что я делаю не так, помогите, пожалуйста. Он ничего не возвращает, но, вероятно, он должен создать файл «Перемещение. json», который содержит такой список:

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

]

1 Ответ

1 голос
/ 07 февраля 2020

Можете ли вы попробовать этот код ниже, и я думаю, что ожидаемый ответ не должен иметь одинаковые имена ключей, поэтому я переименовал его в 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'}]

Использование полный список way:

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 - Здесь мы объединяем значения student_name в список ученика
  • Сортировать список диктов по значению - Ref: Проверьте эту ссылку Есть и много других способов
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'}]
...