Different types of python dictionaries

Asked

Viewed 132 times

5

Is there any way to convert this dictionary:

d = {'Ano; Dia; Mes' : '1995; 2; 5'}

for this format:

d = {'Ano': '1995'; 'Dia' : '2'; 'Mes': '5'}

Thank you

1 answer

7


First I get the keys ( d.keys() ) and turn it into a list, then I take the first element ( of value 0, 'Ano; Dia; Mes' ) and separate them from "; "

getting a list : ['Ano', 'Dia', 'Mes'].

Then I do the same with values ( d.values() ).

So then I put these values inside the dictionary using the for.

It got a little confusing, but I can understand...

Thus remaining:

d = {'Ano; Dia; Mes' : '1995; 2; 5'}
d2 = {}

chaves = list(d.keys())
valores = list(d.values())

chaves = chaves[0].split('; ')
valores = valores[0].split('; ')

for i in range(len(chaves)):
    d2[chaves[i]] = valores[i]

print(d2)

Exit:

>>> {'Ano': '1995', 'Mes': '5', 'Dia': '2'}
  • This is exactly what I needed! Thank you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.