anouar.bag
0
Q:

get a value from a dictionary python

dictionary = {"message": "Hello, World!"}

data = dictionary.get("message", "")

print(data)  # Hello, World!
9
#!/usr/bin/python

dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" %  dict.get('Age')
print "Value : %s" %  dict.get('Education', "Never")
1
dic = {"A":1, "B":2} 
print(dic.get("A")) 
print(dic.get("C")) 
print(dic.get("C","Not Found ! ")) 
4
dict = {'color': 'blue', 'shape': 'square', 'perimeter':20}
dict.get('shape') #returns square

#You can also set a return value in case key doesn't exist (default is None)
dict.get('volume', 'The key was not found') #returns 'The key was not found'
8
# The get() method on dicts
# and its "default" argument

name_for_userid = {
    382: "Alice",
    590: "Bob",
    951: "Dilbert",
}

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

>>> greeting(382)
"Hi Alice!"

>>> greeting(333333)
"Hi there!"

'''When "get()" is called it checks if the given key exists in the dict.

If it does exist, the value for that key is returned.

If it does not exist then the value of the default argument is returned instead.
'''
# transferred by @ebdeuslave
# From Dan Bader - realpython.com
6
print(dict["key"])
2
# Get a value from a dictionary in python from a key

# Create dictionary
dictionary = {1:"Bob", 2:"Alice", 3:"Jack"}

# Retrieve value from key 2
entry = dictionary[2]

# >>> entry
# Alice
-1

  
    dictionary.get(keyname, value)
  
2

New to Communities?

Join the community