fromkeys method | copy method | clear method | get method in dictionary | python

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:

Dictionary in Python

Convert list into Dictionary using Dict.fromkeys python Ex-2

dictionary2 = dict.fromkeys([‘name’,’age’,’height’],’unknown’)

print(dictionary2)

Output:

fromkeys method | Convert list into Dictionary using Dict.fromkeys python

Convert Tuple into Dictionary using Dict.fromkeys python Ex-3

dictionary3 = dict.fromkeys((‘name’,’age’,’height’),’unknown’)

print(dictionary3)

Output:

Convert Tuple into Dictionary using Dict.fromkeys python

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:

String as dictionary key in Python

Range as dictionary key in Python Ex-5

dictionary5 = dict.fromkeys(range(1,5),’unknown’)

print(dictionary5)

Output:

Range as dictionary key in Python

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:

Leave a Reply

%d bloggers like this: