0

Below code does not work, data is a dictionary & I was wondering how to pass it to function

def my_function(x={}):
for i , j in x:
    print (i)
    print (j)

data = {'a':1, 'b': 2, 'c': 3}
my_function(**data)
4
  • 1
    Have you tried simply passing the dictionary as an argument? my_function(data) Commented Apr 6, 2018 at 8:17
  • its not a good practice to have default argument value mutable! Commented Apr 6, 2018 at 8:20
  • 1
    @AmitKarnik it's not that it's not "good practice", but that it doesn't work as most peoples would expect docs.python-guide.org/en/latest/writing/gotchas/… Commented Apr 6, 2018 at 8:39
  • yes, that's what I wanted to say. Anyway, thanks. Commented Apr 9, 2018 at 5:18

1 Answer 1

2

The below code should work for you:

def my_function(x={}):
    for i, j in x.iteritems():
        print (i)
        print (j)

data = {'a':1, 'b': 2, 'c': 3}
my_function(data)

Explanation

  • Ensure your indentation is correct.
  • To iterate a dictionary, use dict.iteritems (in Python 2.x) or dict.items (in Python 3).
  • If you are iterating the dictionary in this way, there is no reason to use an unpacking ** operator.
  • Understand the pitfalls of using Mutable Default Arguments.
Sign up to request clarification or add additional context in comments.

2 Comments

Just beware of the mutable default argument gotcha if your real function mutates it's argument (docs.python-guide.org/en/latest/writing/gotchas/…)
@brunodesthuilliers, good point - in this specific usage not an issue, but I'll add that link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.