+ 1
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
5 Respostas
+ 5
you are trying to print a dictionary, and that is why you are getting the error. you need to print only the part of the dict you want to see, or iterate through it and print each part individually. you can try this
change the following
return dict
to
return dict["c"]
though I think dict is a keyword and might not be a smart choice for a variable name..
or try it this way
my_dict = func(num)
print(my_dict["c"])
this is because the function returns an entire dictionary, not just one element in it.
also, its important to realize that your function changes the original dictionary, so there is no need to return anything at all.
func(num)
print(num["c"])
+ 1
def func(dict):
if dict["a"] == dict["b"]:
dict["c"] = dict["a"]
return dict
num = { "a": 1, "b": 2, "c": 3}
print(func(num))
this code works.
Double quotes were missing. Also python is case sensitive. so its 'if' , not 'If'
0
pass a whole dict the same as any other variable. no need for the **
0
@Luke: First i tried 'print(func(num))'. It also had the same TypeError. So after searching the net, i found this:
http://stackoverflow.com/a/21986301
Thats why i used **num, but still the TypeError msg continues.
0
try this.
def myfnc(mydict={},**kwargs):
for names,numbers in mydict:
#write conditions you want to check for here
# to use if statements you write
if numbers>0: or whichever condition you want to write.
# if you write if mydict[names]>0: it will give some errors
# if you want to call the function, say
myfnc(phonebook)
# assuming phonebook is your dictionary