convert python dictionary to string

2.4k views Asked by At

I have a list of python dictionaries. How to convert python dictionary from

{'foo1':['bar1','bar2'] , 'foo2':['bar3']}
{'foo3':['bar4','bar5','bar6'] , 'foo4':['bar7','bar8','bar9']}
.
.
.
{'foo5':['bar10'] , 'foo6':['bar11','bar12']}
{'foo7':['bar13','bar14'] , 'foo8':['bar15','bar16','bar17','bar18']}

to

{foo1 = ['bar1','bar2'] , foo2 = ['bar3']}
{foo3 = ['bar4','bar5','bar6'] , foo4 = ['bar7','bar8','bar9']}
.
.
.
{foo5 = ['bar10'] , foo6 =['bar11','bar12']}
{foo7 = ['bar13','bar14'] , foo8 = ['bar15','bar16','bar17','bar18']}

Need to output this to a file for icinga dictionaries.

2

There are 2 answers

0
Artyer On BEST ANSWER

You can iterate over the keys and values, then join them with a , and surround them with {}:

def icinga_form(d):
    items = ', '.join(
        '{} = {}'.format(key, value) for key, value in d.items()
    )
    return '{%s}' % (items,)

And then apply it to every item with a map:

list_of_dicts = [
    {'foo1': ['bar1', 'bar2'], 'foo2': ['bar3']},
    {'foo3': ['bar4', 'bar5', 'bar6'], 'foo4': ['bar7', 'bar8', 'bar9']},
    ...,
    {'foo5': ['bar10'], 'foo6': ['bar11', 'bar12']},
    {'foo7': ['bar13', 'bar14'], 'foo8': ['bar15', 'bar16', 'bar17', 'bar18']}
]

list_of_icinga = map(icinga_form, list_of_dicts)

for s in list_of_icinga:
    print(s)
{foo1 = ['bar1', 'bar2'], foo2 = ['bar3']}
{foo3 = ['bar4', 'bar5', 'bar6'], foo4 = ['bar7', 'bar8', 'bar9']}
...
{foo5 = ['bar10'], foo6 = ['bar11', 'bar12']}
{foo7 = ['bar13', 'bar14'], foo8 = ['bar15', 'bar16', 'bar17', 'bar18']}
0
t.hall On

If you want it to be that exact string (I don't know why) this should work:

def dict2str(dict):
    mystr = ''
    for item in dict:
        if mystr == '':
            mystr = item + ' = ' + str(dict[item])
        else:
            mystr = mystr + ' , ' + item + ' = ' + str(dict[item])
    mystr = "{" + mystr + "}"
    return(mystr)

But keep in mind that dictionaries are not ordered so you might have issues getting that exact patterned returned.