简体   繁体   中英

Unpacking multiple lists and dictionaries as function arguments in Python 2

Possible Relevant Questions (I searched for the same question and couldn't find it)


Python makes a convenient way to unpack arguments into functions using an asterisk, as explained in https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

In my code, I'm calling a function like this:

def func(*args):
    for arg in args:
        print(arg)

In Python 3, I call it like this:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

func(*a, *b, *c)

Which outputs

1 2 3 4 5 6 7 8 9

In Python 2, however, I encounter an exception:

>>> func(*a, *b, *c)
  File "<stdin>", line 1
    func(*a, *b, *c)
             ^
SyntaxError: invalid syntax
>>> 

It seems like Python 2 can't handle unpacking multiple lists. Is there a better and cleaner way to do this than

func(a[0], a[1], a[2], b[0], b[1], b[2], ...)

My first thought was I could concatenate the lists into one list and unpack it, but I was wondering if there was a better solution (or something that I don't understand).

d = a + b + c
func(*d)

Recommendation: Migrate to Python 3
As of January 1, 2020, the 2.x branch of the Python programming language is no longer supported by the Python Software Foundation.

Unpacking Lists and passing to *args

Python 3 Solution

def func(*args):
    for arg in args:
        print(arg)

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

func(*a, *b, *c)

Python 2 Solution

If Python 2 is required, then itertools.chain will provide a workaround:

import itertools


def func(*args):
    for arg in args:
        print(arg)

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

func(*itertools.chain(a, b, c))

Output

1
2
3
4
5
6
7
8
9

Unpacking Dictionaries and passing to **kwargs

Python 3 Solution

def func(**args):
    for k, v in args.items():
        print(f"key: {k}, value: {v}")


a = {"1": "one", "2": "two", "3": "three"}
b = {"4": "four", "5": "five", "6": "six"}
c = {"7": "seven", "8": "eight", "9": "nine"}

func(**a, **b, **c)

Python 2 Solution

As Elliot mentioned in the comments, if you need to unpack multiple dictionaries and pass to kwargs , you can use the below:

import itertools

def func(**args):
    for k, v in args.items():
        print("key: {0}, value: {1}".format(k, v))


a = {"1": "one", "2": "two", "3": "three"}
b = {"4": "four", "5": "five", "6": "six"}
c = {"7": "seven", "8": "eight", "9": "nine"}

func(**dict(itertools.chain(a.items(), b.items(), c.items())))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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