Monday 4 September 2017

Python dict


The difference while using get() is that it returns None instead of KeyError, if the key is not found.


my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']

Python Dictionary Methods
MethodDescription
clear()Remove all items form the dictionary.
copy()Return a shallow copy of the dictionary.
fromkeys(seq[, v])Return a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d])Return the value of key. If key doesnot exit, return d(defaults to None).
items()Return a new view of the dictionary's items (key, value).
keys()Return a new view of the dictionary's keys.
pop(key[,d])Remove the item with key and return its value or d if keyis not found. If d is not provided and key is not found, raises KeyError.
popitem()Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d])If key is in the dictionary, return its value. If not, insert keywith a value of d and return d (defaults to None).
update([other])Update the dictionary with the key/value pairs from other, overwriting existing keys.
values()Return a new view of the dictionary's values








No comments:

Post a Comment