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

3
  • 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)? Commented Oct 6, 2016 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. stackoverflow.com/a/21986301 Commented Oct 6, 2016 at 23:41
  • Possible duplicate: stackoverflow.com/questions/36901/… Commented Oct 6, 2016 at 23:55

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

The first one should be print(func(num)), shouldn't it?
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}

1 Comment

Also, it would be good to point out that using dict for a name is usually a very silly decision.
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_ ))

1 Comment

hi, eman please add space/tab in python program, as space/tab syntax is important in python.

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.