简体   繁体   English

在函数参数python中传递多个字典

[英]Passing multiple dictionaries in function parameter python

I have a function which takes more than one dictionary as its parameter. 我有一个函数,需要多个字典作为参数。 I am having an issue with Syntax as i keep getting the following message: 我遇到语法问题,因为我不断收到以下消息:

SyntaxError: non-keyword arg after keyword arg

Essentially , my code will run through each item in the file_names list and grab the file size for each one to be passed on my compare() function. 本质上,我的代码将遍历file_names列表中的每个项目,并获取要在我的compare()函数中传递的每个项目的文件大小。 I am having issues with passing multiple dictionaries. 我在传递多个字典时遇到问题。 There are two keys for each dictionary and they are File Name and File Size. 每个词典有两个键,分别是“文件名”和“文件大小”。 My code is as follows : 我的代码如下:

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})

An argument is a single object, so func(arg1={}, {}) is not passing two dicts as "arg1" but one dict as (named argument) "arg1" and the second as a positional argument - and as you noticed, python forbids passing positional arguments after named ones (since it cannot know which parameter the positional argument would match). 参数是单个对象,因此func(arg1={}, {})不会将两个字典传递为“ arg1”,而是将一个字典传递为(命名参数)“ arg1”,将第二个字典传递为位置参数-正如您所注意到的,python禁止在命名参数之后传递位置参数(因为它不知道位置参数将匹配哪个参数)。

If you want to pass more than one dict as "previous_data" and "current_data", you have to pass a collection of dict (in this cas a list is the very obvious choice), ie: 如果要传递多个dict作为“ previous_data”和“ current_data”,则必须传递dict集合(在这种情况下,列表是非常明显的选择),即:

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

Now this also means you have to (re)write your functions in such a way that it expects lists of dicts, not dicts. 现在这也意味着您必须以一种要求字典列表而不是字典的方式来(重新)编写函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM