1

I have this list:

['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa']

(I am getting this list from xml file by making a parser)and I want to convert it into a dictionary like this:

{'Leistung': ['15 kW','25 kW'], 'Farbe': 'Rot', 'Hersteller': ['Peugeot','VW Nordamerika und Europa']}

I am new to python and I have tried so many codes but it is not working

Following is my code for the parser getting the list from the xml file:

import os

from xml.etree import ElementTree

file_name = 'data.xml'

full_file = os.path.abspath(os.path.join('data', file_name))

dom = ElementTree.parse(full_file)

autos = dom.findall('auto')

n = 6

dictionary = {}

mylist = []

for a in range(n):

    for c in autos:

        key = c.find('Key')

        value = c.find('Value')

        mylist.append(key.text)

        mylist.append(value.text)

    break

print(mylist)
ANA
  • 83
  • 5
  • Does this answer your question? [Convert a list to a dictionary in Python](https://stackoverflow.com/questions/4576115/convert-a-list-to-a-dictionary-in-python) – Nathan Chappell Feb 22 '20 at 23:31
  • Have you considered that single items in your dictionary should probably also be in a list (of one element), so that you can expect every value of the dictionary to be a list? This will make other code that interacts with the dictionary likely a lot easier to code. (and I don't think all cars are red anyway) – Grismar Feb 23 '20 at 00:25

2 Answers2

1

This is a perfect job for defaultdict

which means no need for indexes/ranges and no need to check if a key is present yet

from collections import defaultdict


lst = ['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa']
res = defaultdict(list)
for k,v in zip(*[iter(lst)]*2):
    res[k].append(v)
print(res)

produces

defaultdict(<class 'list'>, {'Leistung': ['15 kW', '25 kW'], 'Farbe': ['Rot'], 'Hersteller': ['Peugeot', 'VW Nordamerika und Europa']})

Of course the assumption is that the input comes in pairs (of key and value), as per your description

Further note: in case you are wondering what the quirky zip does and how it works, please read here

Pynchia
  • 10,996
  • 5
  • 34
  • 43
0

I am assuming the keys are located every two items in the list.

l = ['Leistung', '15 kW', 'Farbe', 'Rot', 'Hersteller', 'Peugeot', 'Leistung', '25 kW', 'Hersteller', 'VW Nordamerika und Europa']
dictionnary = {}

for i in range(0, len(l) - 1, 2):
    key = l[i]
    if key not in dictionnary: dictionnary[key] = [l[i+1]]
    else: dictionnary[key].append(l[i+1])
espilon
  • 29
  • 1
  • 5
  • This solution is inefficient and redundant. Not pythonic at all. Please take time to study the iteration protocol and experiment with all the features provided by python's standard library. One excellent resource is [PyMOTW](https://pymotw.com/3/) – Pynchia Feb 23 '20 at 06:23