Home > Blockchain >  How to print the values of keys here?
How to print the values of keys here?

Time:03-04

I gave some values & keys in a dictionary & showed the value of two keys present here.

def save_user_1(**user):
    return user["id"], user["mail"]

print(save_user_1(id = 1, name = "john", mail = "[email protected]"))

Output : (1, '[email protected]')

1.Why does it show the output as a tuple here?

2.How can I get the values of keys here ?(The oppposite of what showed in the output)

CodePudding user response:

  1. To get a list as output, use brackets : return [user["id"], user["mail"]]
  2. You can try user.keys() to get the dictionary keys, or user.items() to get both keys and values :
def save_user_1(**user):
    print('user keys', user.keys())
    for key, value in user.items():
        print("key =", key, ", value =", value)
    return user["id"], user["mail"]

print(save_user_1(id = 1, name = "john", mail = "[email protected]"))

output :

user keys dict_keys(['id', 'name', 'mail'])
key = id , value = 1
key = name , value = john
key = mail , value = [email protected]
(1, '[email protected]')

CodePudding user response:

  1. Because user["id"], user["mail"] is a tuple, same as (user["id"], user["mail"]).
  2. You are getting the values for the keys 'id' and 'mail'. If you want the keys (I'm not sure why you would) you could return [k for k in ('id', 'mail') if k in user].

CodePudding user response:

When you do return user["id"], user["mail"] you are telling python to return a tuple. Could you add to your question what kind of output you would like from print?

  • Related