Как объединить словарь с таким же ключом? - PullRequest
0 голосов
/ 24 октября 2018

Я хочу объединить приведенный ниже код с Keys Action и Thriller.Будут присутствовать только 2 клавиши {'Действие': [список фильмов], 'Триллер': [список фильмов]}.Также приветствуется новый код, например lxml или BeautifulSoup.

Мой код указан ниже:

import xml.etree.ElementTree as ET
from collections import defaultdict
tree = ET.parse('movies.xml')
root = tree.getroot()
d = {}
for child in root:
    #print( child.attrib.values())
    for movie in root.findall("./genre/decade/movie[@title]"):
    #print(movie.attrib)
        #print (list(movie.attrib.values())[1])
        d[child.attrib.values()]=list(movie.attrib.values())[1]
d

Мой вывод

 {dict_values(['Action']): 'Indiana Jones: The raiders of the lost Ark',
 dict_values(['Action']): 'THE KARATE KID',
 dict_values(['Action']): 'Back 2 the Future',
 dict_values(['Action']): 'X-Men',
 dict_values(['Action']): 'Batman Returns',
 dict_values(['Action']): 'Reservoir Dogs',
 dict_values(['Action']): 'ALIEN',
 dict_values(['Action']): "Ferris Bueller's Day Off",
 dict_values(['Action']): 'American Psycho',
 dict_values(['Thriller']): 'Indiana Jones: The raiders of the lost Ark',
 dict_values(['Thriller']): 'THE KARATE KID',
 dict_values(['Thriller']): 'Back 2 the Future',
 dict_values(['Thriller']): 'X-Men',
 dict_values(['Thriller']): 'Batman Returns',
 dict_values(['Thriller']): 'Reservoir Dogs',
 dict_values(['Thriller']): 'ALIEN',
 dict_values(['Thriller']): "Ferris Bueller's Day Off",
 dict_values(['Thriller']): 'American Psycho'}

Мой xml получен из datacamp.Лагерь данных предоставляет информацию об утилизации. Ниже приведен файл xml, который я сохранил в своей локальной папке и назвал его фильмом

<?xml version="1.0" encoding="UTF-8" ?>
<collection>
    <genre category="Action">
        <decade years="1980s">
            <movie favorite="True" title="Indiana Jones: The raiders of the lost Ark">
                <format multiple="No">DVD</format>
                <year>1981</year>
                <rating>PG</rating>
                <description>
                'Archaeologist and adventurer Indiana Jones 
                is hired by the U.S. government to find the Ark of the 
                Covenant before the Nazis.'
                </description>
            </movie>
               <movie favorite="True" title="THE KARATE KID">
               <format multiple="Yes">DVD,Online</format>
               <year>1984</year>
               <rating>PG</rating>
               <description>None provided.</description>
            </movie>
            <movie favorite="False" title="Back 2 the Future">
               <format multiple="False">Blu-ray</format>
               <year>1985</year>
               <rating>PG</rating>
               <description>Marty McFly</description>
            </movie>
        </decade>
        <decade years="1990s">
            <movie favorite="False" title="X-Men">
               <format multiple="Yes">dvd, digital</format>
               <year>2000</year>
               <rating>PG-13</rating>
               <description>Two mutants come to a private academy for their kind whose resident superhero team must 
               oppose a terrorist organization with similar powers.</description>
            </movie>
            <movie favorite="True" title="Batman Returns">
               <format multiple="No">VHS</format>
               <year>1992</year>
               <rating>PG13</rating>
               <description>NA.</description>
            </movie>
               <movie favorite="False" title="Reservoir Dogs">
               <format multiple="No">Online</format>
               <year>1992</year>
               <rating>R</rating>
               <description>WhAtEvER I Want!!!?!</description>
            </movie>
        </decade>    
    </genre>
    <genre category="Thriller">
        <decade years="1970s">
            <movie favorite="False" title="ALIEN">
                <format multiple="Yes">DVD</format>
                <year>1979</year>
                <rating>R</rating>
                <description>"""""""""</description>
            </movie>
        </decade>
        <decade years="1980s">
            <movie favorite="True" title="Ferris Bueller's Day Off">
                <format multiple="No">DVD</format>
                <year>1986</year>
                <rating>PG13</rating>
                <description>Funny movie about a funny guy</description>
            </movie>
            <movie favorite="FALSE" title="American Psycho">
                <format multiple="No">blue-ray</format>
                <year>2000</year>
                <rating>Unrated</rating>
        <description>psychopathic Bateman</description>
            </movie>
        </decade>
    </genre>
</collection>
.

1 Ответ

0 голосов
/ 25 октября 2018

Ваш код отлично работает при получении данных, это просто то, как вы их анализируете.В диктовке .values() возвращает представление значений, которые вы можете сохранить в списке, если хотите.В этом случае вы хотите значение самого словаря, который вы можете просто выбрать по ключу;child.attrib['category'].Как только вы это получите, все, что вам нужно сделать, это обновить ваш диктат.Здесь мы будем использовать defaultdict, который, когда ключ встречается в первый раз, возвращает пустой список, чтобы мы могли добавлять названия фильмов.

import xml.etree.ElementTree as ET
from collections import defaultdict

tree = ET.parse('movies.xml')
root = tree.getroot()
d = defaultdict(list)

for child in root:
    for movie in root.findall("./genre/decade/movie[@title]"):
        d[child.attrib['category']].append(movie.attrib['title'])

>>d

defaultdict(list,
            {'Action': ['Indiana Jones: The raiders of the lost Ark',
              'THE KARATE KID',
              'Back 2 the Future',
              'X-Men',
              'Batman Returns',
              'Reservoir Dogs',
              'ALIEN',
              "Ferris Bueller's Day Off",
              'American Psycho'],
             'Thriller': ['Indiana Jones: The raiders of the lost Ark',
              'THE KARATE KID',
              'Back 2 the Future',
              'X-Men',
              'Batman Returns',
              'Reservoir Dogs',
              'ALIEN',
              "Ferris Bueller's Day Off",
              'American Psycho']})

Если вы хотите выбрать только сказать «Действие»', вы можете просто выбрать, как обычный словарный ключ.

d['Action']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...