Menu Bar

Horizontal Scrollable Menu

Search This Blog

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

fromkeys method in Python

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.

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

This is because each element is referenced to the same object (indicating the same object in 

To avoid this problem, we use dictionary comprehension.

---> In this if you want to assine same value

into all key of dictionary

dictionary1 = {'name':'unknown','age':'unknown',
  # OR
dictionary2 = dict.fromkeys(['name','age','height'

 # OR

 dictionary5 = dict.fromkeys(('name','age','height'

 {'name': 'unknown', 'age': 'unknown', 'height': 
 # OR

dictionary3 = dict.fromkeys("ABCD",'unknown')


 {'A': 'unknown', 'B': 'unknown', 'C': 'unknown', 
'D': 'unknown'}  
     ## OR

dictionary4 = dict.fromkeys(range(1,5),'unknown')

 1: {'unknown', 2: 'unknown', 3: 'unknown', 

4: 'unknown'}

get method


The python dictionary method () returns a value
for the given key. If the key is not available,
 no one returns the default value.

The following is the syntax for the () method -

dict.get (key, default = none)
Key - This is the key to be searched in the 

Default - This is a value that is not present 
in the key.

return value
This method returns a value for the given key. 
If the key is not available, no one returns the
 default value.

The following example demonstrates the use of the
 get () method.

live demo
#! / Usr / bin / python

Dictator = {'name': 'zebra', 'age': 7}
Print "value:% s"% dict.get ('age')
Print "value:% s"% dictatorship ('education', "never")
When we run over the program, it produces the following result

Value: 7
Price: Never
dict1 = {'name': 'pramod', 'age': 'unknown',
'height': 'unknown'}

# OutPut = pramod

 print(dict1['name'])    # error

#But if key are not availalble and you want to 
print then it will so error

# But if you use get method then it will not show
error // its will give none which mean not 
print(dict1.get('name'))  #OutPut = pramod

 print(dict1.get('names')) # OutPut = none

# get method using in loop or in condition

The get() method returns the value for the specified key if
 key is in dictionary.
if 'name' in dict1:
    print('not present')
 OUTPUT = present

if dict1.get('abcde'):
    print('not present')

 OUTPUT = not present

# clear method

The clear() method removes all items from the list.

print(dict1)     # OUTPUT = {}

# Copy method

The copy() method returns a shallow copy of the list.
dict2 = dict1.copy()


 {'name': 'pramod',
 'age': 'unknown', 'height': 'unknown'}

The copy module contains 2 functions, copy () 
and deepcopy () to duplicate existing objects.

Shallow copies
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

Class MyClass:
def __init __ (self, name):
Selfname = name
def __cmp __ (self, other):
Return cmp (,

a = MyClass ('a')
l = [a]
Dup = copy.copy (l)

Print 'L:', L
Print 'Dup:', Dup
Print 'Dup L Hai:', (Dup L Hai)
Print 'dup == l:', (dup == l)
Print 'dip [0] l [0]:', (dip [0] l [0] is)
Print 'dip [0] == l [0]:', (dip [0] == l [0])
For the shallow copy, the MyClass instance is not
 duplicated, so the reference in the diplist is in
 the same list as the L list.

$ Python

l: [<__ main __. Myxass example 0x100467d88>]
Dip: [<__ main __. Myxass example 0x100467d88>]
Duplicate: False
Dup == Le: true
Dup [0] l [0]: is true
Bip [0] == l [0]: true
Deep copies
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.

Dup = copy.deepcopy (l)
Note that the first element of the list is no 
longer the same object reference, but the two 
objects still evaluate as being identical.

$ python

l: [<__ main __. Myxass example 0x100467d88>]
Dip: [<__ main __. Example 0x100467dd0>of myClass]
Duplicate: False
Dup == Le: true
BiP [0] L [0]: False
Bip [0] == l [0]: true
Copy behavior control
It is possible to control how copies are made 
using the __copy__ and __deepcopy__ hooks.

__copy __ () is called without any arguments and 
should return a shallow copy of the object.
__deepcopy __ () is called with a memo dictionary,
 and it should return a deep copy of the object. 
Any member attributes need to be deep-copied, 
which must be passed to copy.deepcopy () along with
 the memo dictionary to control for repetition 
(see below).
This example shows how the methods are called:

Import copy

Class MyClass:
def __init __ (self, name):
Selfname = name
def __cmp __ (self, other):
Return cmp (,
Dy __copy __ (self):
Print '__copy __ ()'
Return myClass (
def __deepcopy __ (self, memo):
Print '__deepcopy __ (% s)'% str (memo)
Return myClass (copy.deepcopy (, memo))

a = MyClass ('a')

sc = copy.copy (a)
dc = copy.deepcopy (a)
$ Python

__copy __ ()
__deepcopy __ ({})
Repetition in deep copy
To avoid the problems of duplicating recurring data 
structures, DeepScopy () uses a dictionary to track
 already copied objects. This dictionary is passed
 by the __deepcopy __ () method, so it can be used 
there as well.

This example shows how an interrelated data 
structure such as a digraph can help protect 
against recurrence by implementing a __deepcopy
 __ () method. This particular example is for 
illustration purposes only, since the default
 implementation of deepcopy () already handles 
iteration cases correctly.

Import copy
Import footprint

Square graph:
def __init __ (self, name, connection):
Selfname = name
self.connections = connection
Add addConnection (self, other):
self.connections.append (other)
def __repr __ (self):
Return '<graph (% s) id =% s>'% (, id (self))
def __deepcopy __ (self, memo):
Print repr (self)
not_there = []
Existing = mem.get (self, not_there)
If not existing
Print 'already ready', repr (existing)
Current withdrawal
pprint.pprint (memo, indent = 4, width = 40)
Dup = graph (copy.deepcopy (, memo), [])
print COPYING TO ', repr (dup)
Memo [Self] = Dup
For oneself in c. Connection:
dup.addConnection (copy.deepcopy (c, memo))
To dunk

Root = graph ('root', [])
a = graph ('a', [root])
B = graph ('b', [a, root])
root.addConnection (a)
root.addConnection (b)

Dup = copy.deepcopy (root)
First, some basic directed graph methods:
 A graph can be started with a name and a list of
 existing nodes to which it is associated. 
The addConnection () method is used to establish 
a bi-directional connection. It is also used by 
the DeepCopy operator.

The __deccopy __ () method prints the messages to
 show how it is called, and the memo dictionary 
manages the content as needed. Instead of copying
 the connection list bulk, it creates a new list 
and adds individual connection copies to it. 
The graph has many cycles, but by handling 
iteration with the memo dictionary we can cause
 an overflow error due to traversal. When the root
 node is copied, we see:

$ Python

<Graph (root) id = 4299639696>
Copying <graph (root) id = 4299640056>

<Graph (a) id = 4299639768>
{<Graph (root) id = 42939349797>: <graph (root) 
id = 72979006>,
4298517936: ['root'],
4299576592: 'root'}
Copying to <graph (a) id = 4299640128>

<Graph (root) id = 4299639696>
Already copied for <graph (original) id=4299640056>

<Graph (b) id = 4299639840>
{<Graph (root) id = 42939349797>: <graph (root) 
id = 72979006>,
<Graph (a) id = 4299639768>: <graph (a) id=4299640128>,
4297844216: 'A',
4298517936: ['root',
<Graph (root) id = 4299639696>,
<Graph (a) id = 4299639768>],
4299576592: 'root',
4299639696: <graph (root) id = 4299640056>,
4299639768: <graph (a) id = 4299640128>}
Copying to <graph (b) id = 4299640632>
The second time a root node is encountered,
while a node is being copied, __deepcopy__ 
recycles and reuses an existing value from the 
memo dictionary instead of creating a new object.

No comments: