Python Program to understand dictionaries.
1. Here I am creating a dictionary.
my_dict1 = {}
using {} for declaring an empty dictionary as dictionaries are declared using {}.
my_dict2 = dict()
using dict() is also a way to declare an empty dictionary.
2. In dictionary we use pairs of key:values.
my_dict1 = {'fruit' : 'apple', 'drink' : "pepsi"}
here we used fruit and drink as a key and apple and pepsi as their values resp.
we can't have two or more keys with same name.
my_dict2 = {'vegetable' : 'carrot', 'fruit' : my_dict1}
here we are declaring a nested dictionary.
3. We can add and update elements in dictionay using a no. of methods. Use [] for accesing a key or adding and updating.
my_dict2['fruit'] = 'orange'
If we use a key which already exist then it updates the previous value.
my_dict2['snacks'] = 'chips', 'cookies'
we are assigning a no. of values to a key and it get stored in the form of tuple(or we can cast it)
my_dict2.update({'snacks' : 'chips'})
here we are updating the existing key and if key doesn't exist then it will add new key.
4. We can access a value inside dictionary using the key associated to it inside a [] and we can also use get method.
print(my_dict1['fruit'])
If key is not present in dictionary then it will give error.
print(type(my_dict1.get('snacks')))
the difference here is, in get(value, default='None') method will return none if key is not present in dictionary.
we can use two arguments in get(). It will return the second value if key is not present.
5. We can remove a key by using the del/clear/pop method.
del my_dict2["fruit"]
here we are deleting a item from the dictionary
my_dict2.pop('vegetable')
here we are using pop(key, default = 'None') method to remove a item from dictionary and return the value associated with key. If item not present in dictionary then it return the second argument.
my_dict2.popitem()
this method will remove the last inserted item in the dictionary and return it as a tuple.
my_dict2.clear()
this method will clear the dictionary.
del my_dict2
this will delete the dictionary.
6. Methods on Dictionaries.
keysl = my_dict1.keys()
it returns a list of keys.
values1 = my_dict1.values()
it returns a list of values in dictionary.
items1 = my_dict1.items()
it returns list of a given dictionary’s (key, value) tuple pair.
my_dict2=my_dict1.copy()
it copies my_dict1 into my_dict2
my_dict3 = dict(my_dict1)
this is also a way to copy a dictionary into another
below method returns a dictionary with the specified keys and the specified value(dictionary.fromkeys(keys,value))
my_dict2 = my_dict3.fromkeys('1', 'none')
print(my_dict2)
dict_comb=my_dict1 | my_dict2
here we are combinig two dictionary
dict_comb2={**my_dict1, **my_dict2}
Using ** we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third.
Top comments (0)