我不明白这个Python代码是如何工作的 - 未知的编程概念

时间:2015-12-22 09:17:26

标签: python dictionary configparser

我为糟糕的标题道歉。如果我能够正确地构建我的问题,我会使用谷歌;)

我找到了一段能够将ini文件解析成名为“store”的python dict的python代码:

#!/usr/bin/env python

from ConfigParser import SafeConfigParser

def read(file, store):

    def parse_maybe(section):
        if not confp.has_section(section):
            return False

        if (section == "Main"):
            for left, right in confp.items(section):
                store[left] = right.format(**store)
        return True

    confp = SafeConfigParser()
    confp.read(file)
    parse_maybe("Main")

store = {}
store["basedir"] = "/path/to/somewhere"
read("foo.ini", store)

ini文件可能包含占位符声明,例如:

[Main]
output = {basedir}/somename.txt

运行代码时,{basedir}将替换为已在商店中定义的“/ path / to / somewhere”。我猜这个魔法来自这行代码:

store[left] = right.format(**store)

我理解代码所做的 。但我不明白 这是如何运作的。这个**运算符用字典做什么?指向教程等的指针将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

我的问题的答案有两个:

1)我不知道格式是否可行:

print "{a} is {b}".format(a="Python", b="great")

Python很棒

2)基本上**运算符解包字典:

dict = {"a": "Python", "b": "great"}
print "{a} is {b}".format(**dict)

Python很棒

相关问题