2

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

Rkumar
  • 127
  • 2
  • 3
  • 10
  • 1
    First change `If` to `if`. Second, do not use `dict` as a parameter or variable name, it is a builtin. Third, why are you saying `func(**num)` instead of `func(num)`? – Christian Dean Oct 06 '16 at 23:34
  • If was a typing error while asking the question. Being a newbie I didn't know dict is reserved key. About using **num, I was trying to follow one of the earlier stack overflow answers. http://stackoverflow.com/a/21986301 – Rkumar Oct 06 '16 at 23:41
  • Possible duplicate: http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters – Dimitris Fasarakis Hilliard Oct 06 '16 at 23:55

3 Answers3

8

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))
Lewis Fogden
  • 515
  • 5
  • 8
5

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}
Prune
  • 76,765
  • 14
  • 60
  • 81
1

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_ ))
Eman Diab
  • 11
  • 2