What does Fromkeys() method do?
The fromkeys () method creates a new dictionary from a given sequence of elements with a value provided by the user. If the value argument is set, then each element of the newly created dictionary is set to the provided value.
Python Dictionary fromkeys() Method Use
If the value provided is a mutated object (whose value can be modified) such as a list, dictionary, etc., when the mutated object is modified, each element of the sequence is also updated.
This is because each element is referenced to the same object (indicating the same object in memory).To avoid this problem, we use dictionary comprehension.
Python Dictionary Fromkeys Method() with Examples
We can create a dictionary in different ways examples are given below. In this, if you want to assign the same value into all key of the dictionary
Dictionary in Python Ex-1
dictionary1 = {‘name’:’unknown’,’age’:’unknown’,’height’:’unknown’}
print(dictionary1)
Output:
Convert list into Dictionary using Dict.fromkeys python Ex-2
dictionary2 = dict.fromkeys([‘name’,’age’,’height’],’unknown’)
print(dictionary2)
Output:
Convert Tuple into Dictionary using Dict.fromkeys python Ex-3
dictionary3 = dict.fromkeys((‘name’,’age’,’height’),’unknown’)
print(dictionary3)
Output:
String as dictionary key in Python Ex-4
In this example first String of each character act as a key and and next string will assign as value in each key.
dictionary4 = dict.fromkeys(“ABCD”,’unknown’)
print(dictionary4)
Output:
Range as dictionary key in Python Ex-5
dictionary5 = dict.fromkeys(range(1,5),’unknown’)
print(dictionary5)
Output:
Empty Key in Dictionay Ex-6
If we are not providing any key values in the dictionary then it will print an empty dictionary.
dictionary5 = dict.fromkeys("",'unknown')
print("The output dictionary is:",dictionary5)
Output:
C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
The output dictionary is: {}
Process finished with exit code 0
How to Print Specific Key Values from a Dictionary
To print the specific key values from a dictionary, we have to follow the given example which is below.
Example1
dict1 = {‘name’: ‘pramod’, ‘age’: ‘unknown’, ‘height’: ‘unknown’}
print(dict1[‘name’]) # It will give proper output
Output:
pramod
But now if I entered ‘name’ as ‘names’ then will show an error. To solve this issue we can use dictionary_name.get(‘key of dictionary’)
Example-2
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
print(dict1['names'])
# It show an error because key is not available
# But if you use get method then it will not show Error. The output will be none which mean such key is not available
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
print(dict1.get('name'))
#OutPut = pramod
print(dict1.get('names'))
# Output = none
How to print dictionary key and values using for loop in python
Use for loop to check value is present in the dictionary
The get() method returns the value for the specified key if the key is in a dictionary.
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
if 'name' in dict1:
print('Present')
else:
print('not present')
OUTPUT
Present
Use dict.get() method to Check value is present in the dictionary Example
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
if dict1.get('abcde'):
print('present')
else:
print('not present')
OUTPUT
not present
Clear() method in Python with Example
The clear() method is used to removes all items from the list.
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
dict1.clear()
print(dict1)
OUTPUT = {}
Copy() Method in Python
The copy() method returns a shallow copy of the list.
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
dict2 = dict1.copy()
print(dict2)
Output:
{'name': 'pramod','age': 'unknown', 'height': 'unknown'}
The copy module contains 2 functions, copy () and deepcopy() to duplicate existing objects.
What is Shallow copy in Python?
The shallow copy() created by the copy is a new container populated in terms of the contents of the original object. For example, a new list is created and elements of the original list are added to it.
import copy
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
dict2 = copy.copy(dict1)
print(dict2)
C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
{'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
Process finished with exit code 0
What is deep copy with example?
Deep copy created by deepcopy () is a new container populated with copies of the contents of the original object. For example, a new list is created and the elements of the original list are copied, then copies are added to the new list. With deepcopy () to copy the call, the difference becomes apparent.
Syntax:
Dup = copy.deepcopy ()
Note that the first element of the list is no longer the same object reference, but the two objects still evaluate as being identical.
Example
import copy
dict1 = {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
dict2 = dict1.copy()
dict3 = copy.deepcopy(dict1)
print("Out put of .copy is:",dict2)
print("Out put of .deepcopy is:",dict3)
Output:
C:\Users\Pramod\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/Pramod/PycharmProjects/pythonProject/main.py
Out put of .copy is: {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
Out put of .deepcopy is: {'name': 'pramod', 'age': 'unknown', 'height': 'unknown'}
Recommended Post:
- Python Hello World Program
- Python Comment | Creating a Comment | multiline comment | example
- Python Dictionary Introduction | Why to use dictionary | with example
- How to do Sum or Addition in python
- Python Reverse number
- find common number in python
- addition of number using for loop and providing user input data in python
- Python Count char in String
- Python Last Character from String
- Python Odd and Even | if condition
- Python Greater or equal number
- Python PALINDROME NUMBER
- Python FIBONACCI SERIES
- Python Dictionary | Items method | Definition and usage
- Python Dictionary | Add data , POP , popitem , update method
- Python Dictionary | update() method
- Delete statement , Looping in list In Python
- Odd and Even using Append in python
- Python | Simple Odd and Even number