将python字典转换为字符串

时间:2017-09-14 21:15:14

标签: python dictionary icinga

我有一个python词典列表。如何从

转换python字典
{'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']}

{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']}

需要将其输出到icinga词典的文件。

2 个答案:

答案 0 :(得分:1)

您可以迭代键和值,然后使用,加入它们并用{}包围它们:

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

然后将其应用于带有地图的每个项目:

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']}

答案 1 :(得分:0)

如果你想要它是那个确切的字符串(我不知道为什么),这应该有效:

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)

但请记住,词典没有订购,因此您可能会遇到问题,确保返回精确的图案。