Dictionaries Continued
-
Assignments:
- As with lists, if you make a change in dictionary, it will reflect to all the names that refer to it
- As with lists, if you make a change in dictionary, it will reflect to all the names that refer to it
-
Shallow Copy
- To copy keys and values from a dictionary to other dictionary we can use copy()
- This method is shallow copy and works if the dictionary values are immutable.
- If you dictionary contains the values which are mutable prefer deepcopy()
-
Deep Copy
-
Iterating dictionary with for and in Refer Here
-
Dictionary Comprehensions:
- The syntax of dictionary comprehensions is
{ key_expression: value_expression for expression in iterable }
- Lets try to count the number of words in a letter and display them as dictionary
word = 'letters' { 'l': 1, 'e': 2, 't': 2, 'r': 1, 's': 1 }
- The program using normal for in will be
word = input('Enter any word: ') letter_dict = {} for letter in word: if letter in letter_dict: letter_dict[letter] += 1 else: letter_dict[letter] = 1 print(letter_dict)
- Refer Here for the dictionary comprehension
- Refer Here for other dictionary methods
Rules of Dictionary
- Keys must be unique
- Keys must be immutable i.e. key can be int, float, string, tuple
Project Euler Problem 5
- Refer Here
- Refer Here for the solution