Rkumar
Rkumar

Reputation: 127

How to pass dictionary as an argument of function and how to access them in the function

I tried doing this:

def func(dict):
    if dict[a] == dict[b]:
        dict[c] = dict[a]
    return dict

num =  { "a": 1, "b": 2, "c": 2}
print(func(**num))

But it gives in TypeError. Func got an unexpected argument a

Upvotes: 2

Views: 25133

Answers (3)

Lewis Fogden
Lewis Fogden

Reputation: 524

Using ** will unpack the dictionary, in your case you should just pass a reference to num to func, i.e.

print(func(num))

(Unpacking ** is the equivalent of func(a = 1, b = 2, c = 3)), e.g.

def func(arg1, arg2):
    return arg1 + arg2

args = {"arg1": 3,"arg2": 4}
print(func(**args))

Upvotes: 8

Eman Diab
Eman Diab

Reputation: 11

You can do it like this i don't know why it works but it just work

gender_ = {'Male': 0, 'Female': 1}

def number_wordy(row, **dic):
   for key, value in dic.items() :
       if row == str(key) :
            return value
print(number_wordy('Female', **gender_ ))

Upvotes: 1

Prune
Prune

Reputation: 77857

Two main problems:

  • passing the ** argument is incorrect. Just pass the dictionary; Python will handle the referencing.
  • you tried to reference locations with uninitialized variable names. Letters a/b/c are literal strings in your dictionary.

Code:

def func(table):
    if table['a'] == table['b']:
        table['c'] = table['a']
    return table

num =  { "a": 1, "b": 2, "c": 2}
print(func(num))

Now, let's try a couple of test cases: one with a & b different, one matching:

>>> letter_count =  { "a": 1, "b": 2, "c": 2}
>>> print(func(letter_count))
{'b': 2, 'c': 2, 'a': 1}

>>> letter_count =  { "a": 1, "b": 1, "c": 2}
>>> print(func(letter_count))
{'b': 1, 'c': 1, 'a': 1}

Upvotes: 5

Related Questions