HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Convert a string into a dictionary

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertintostringdictionary

Problem

I have a string like "food | dairy | milk". The string may consist of more or less words. How do I turn it into a dictionary {'food': {'dairy': {'milk': {'eco': {}}}}}?

The only way I could achieve it was to create a string and then turn it into a dictionary using exec. I understand it's messy. How could I improve on it?

#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-
# I have a string that represents 'path' to place where new item should be inserted
st="food | dairy | milk"
print st,"< -- string"
keys=st.split(" | ")
print keys,"<-- keys"

new_cat="eco" # should be added
d = {i:{} for i in keys}
print d,"d"

ex_str="{"
for i in keys:
    ex_str+="\""+i+"\":{"
ex_str+="\""+str(new_cat)+"\":{}"+"}"*(len(keys)+1)
exec"nd="+ex_str
print nd,"<-- new dict"

Solution

You use a temporary variable:

st="food | dairy | milk"
keys=st.split(" | ")

new_cat="eco" # should be added
d = t = {} # t is my temporary dictionary

for i in keys:
    t[i] = {}
    t = t[i]
t[new_cat] = {}

print d

Code Snippets

st="food | dairy | milk"
keys=st.split(" | ")

new_cat="eco" # should be added
d = t = {} # t is my temporary dictionary

for i in keys:
    t[i] = {}
    t = t[i]
t[new_cat] = {}

print d

Context

StackExchange Code Review Q#90253, answer score: 3

Revisions (0)

No revisions yet.