【问题标题】:Passing multiple dictionaries in function parameter python在函数参数python中传递多个字典
【发布时间】:2019-05-19 02:24:29
【问题描述】:

我有一个函数,它接受多个字典作为其参数。我遇到了语法问题,因为我不断收到以下消息:

SyntaxError: non-keyword arg after keyword arg

本质上,我的代码将遍历 file_names 列表中的每个项目,并获取要传递给我的 compare() 函数的每个项目的文件大小。我在传递多个字典时遇到问题。每个字典有两个键,它们是文件名和文件大小。我的代码如下:

def compare(previous,current):

    tolerance = 0.4

    if previous is None and current is None:
        return " missing in both"

    if previous is None:
        return " new"

    if current is None:
        return " missing"

    size_ratio = float(current)/previous

    if size_ratio >= 1 + tolerance:
        return " %d%% bigger" % round(((size_ratio - 1) * 100),0)

    if size_ratio <= 1 - tolerance:
        return " %d%% smaller" % round(((1 - size_ratio) * 100),0)

    return " ok"


def compare_filesets(file_names, previous_data, current_data):


    for item in file_names:

     print (item + compare(previous_data.get('File Size'), current_data.get('File Size')) + "\n")



compare_filesets(file_names=['a.json', 'b.json', 'c.json'],
                 current_data= {"File Name": "a.json", "File Size": 1000}, {"File Name": "a.json", "File Size": 1000},
                 previous_data={"File Name": "a.json", "File Size": 1000}, {"File Name": "a.json", "File Size": 1000})

【问题讨论】:

  • comparse_filesets 参数不是关键字参数,您正在使用它们。只需按正确的顺序传递数据,不要使用参数名称
  • @yorodm 不正确。每个位置或关键字参数都可以按名称传递。问题是f(a=1, b=2,3, c=4,5) 应该是f(a=1, b=[2,3], c=[4,5])。
  • @DanD。我站得更正了。没有在我的设备上向右滚动。
  • 我想在一个完整的字典中传递文件名和文件大小。例如:current_data = a.json:1000, b.json:100, c.json:1000 和previous_data一样@DanD
  • 你的意思是current_data = {'a.json':1000, 'b.json':100 , 'c.json':1000}?

标签: python python-2.7 list dictionary for-loop


【解决方案1】:

一个参数是一个单一的对象,所以func(arg1={}, {}) 不是将两个字典作为“arg1”传递,而是一个字典作为(命名参数)“arg1”,第二个作为位置参数 - 正如你所注意到的,python 禁止传递命名参数之后的位置参数(因为它不知道位置参数将匹配哪个参数)。

如果你想传递多个dict作为“previous_data”和“current_data”,你必须传递一个dict的集合(在这种情况下,列表是非常明显的选择),即:

somefunc(a=[{}, {}], b=[{}, {}])

现在这也意味着您必须(重新)编写您的函数,使其需要字典列表,而不是字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多