Home > Net >  Turn python list item into dictionary key-value pair
Turn python list item into dictionary key-value pair

Time:10-19

I’m trying to turn the following list:

['06/07/20\n 22,43€ gas\n 34,70€ street toll, ' 08/07/20\n 74,90€ street toll, ' 13/07/20\n 78€ street toll\n 157,90€ gas']

into a dictionary like this:

{'06/07/20':['22,43€ gas', '34,70€ street toll'],'08/07/20':['74,90€ street toll'],'13/07/20':['78€ street toll', '157,90€ gas']}

What I did was:


for i in parsf2:
    if "/" in i:
        new_dict[i]=i
    elif "/" not in i:
         new_dict[i]=i
    else:
        x.append(i)
print(new_dict)

And my current result is:

{'06/07/20\n': '06/07/20\n', '22,43€ gas\n': '22,43€ gas\n', '34,70€ street toll\n': '34,70€ street toll\n', '\n': '\n', '08/07/20\n': '08/07/20\n', '74,90€ street toll\n': '74,90€ street toll\n', '13/07/20\n': '13/07/20\n', '78€ street toll\n': '78€ street toll\n', '157,90€ gas': '157,90€ gas'}

How could I easily fix my beginner's code?

CodePudding user response:

You can do

a = ['06/07/20\n 22,43€ gas\n 34,70€ street toll', ' 08/07/20\n 74,90€ street toll', ' 13/07/20\n 78€ street toll\n 157,90€ gas']
d = {k.splitlines()[0] : list(map(str.strip, k.splitlines()[1:])) for k in a }

output

{'06/07/20': [' 22,43€ gas', ' 34,70€ street toll'],
 ' 08/07/20': [' 74,90€ street toll'],
 ' 13/07/20': [' 78€ street toll', ' 157,90€ gas']}

CodePudding user response:

Try:

lst = [
    "06/07/20\n 22,43€ gas\n 34,70€ street toll",
    " 08/07/20\n 74,90€ street toll",
    " 13/07/20\n 78€ street toll\n 157,90€ gas",
]

out = {}
for v in lst:
    s = v.split(maxsplit=1)
    if len(s) == 2: 
        k, v = s
        out[k] = [w.strip() for w in v.splitlines()]

print(out)

Prints:

{
    "06/07/20": ["22,43€ gas", "34,70€ street toll"],
    "08/07/20": ["74,90€ street toll"],
    "13/07/20": ["78€ street toll", "157,90€ gas"],
}

EDIT: Short explanation:

I iterate over each value of lst and split it to date (first part) and the rest (using str.split with maxsplit=1 parameter)

Then I split the rest over lines (\n) and strip whitespaces, storing the result in out dictionary.

CodePudding user response:

final_result = {}
for entry in parsf2:
    entries = entry.split("\n")
    final_result[entries[0]] = entries[1:]

>>> final_result
{'06/07/20': [' 22,43€ gas', ' 34,70€ street toll'], ' 08/07/20': [' 74,90€ street toll'], ' 13/07/20': [' 78€ street toll', ' 157,90€ gas']}
 

CodePudding user response:

You can do with split and dict comprehension,

In [1]: {i.split(maxsplit=1)[0]:i.split(maxsplit=1)[1].split('\n') for i in lst}
Out[1]: 
{'06/07/20': ['22,43€ gas', ' 34,70€ street toll'],
 '08/07/20': ['74,90€ street toll'],
 '13/07/20': ['78€ street toll', ' 157,90€ gas']}
  • Related