Updating Python dict at the time of initialization

Question:

I was just playing around with Python’s dictionaries and lists. And I found these weird things –

At the time of initialization of any Python dict, list or some other data types, you can’t perform operations of that data type.

# Case 1
d1 = {}
d1.update({'a': 'A'})
print(d1)

# Case 2
d2 = {}.update({'p': 'P'})
print(d2)

Output:

{'a': 'A'}
None

The weird thing is, neither d2 initialized not it threw any error.

What I think about this?

Well, "Python’s interpreter reads code line by line". So, when it reads the line d1 = {} it saves d1 and it’s type (dict) in memory.

But this is not happening with d2 = {}.update({'p': 'P'})

Any operation of dict can be performed on dict object, which in the second case never initiated, ie. dictionary object was never created.

What you think about this?

Please drop your answers and correct me, if I was wrong. Which I guess, I may be.

Asked By: Rajesh Joshi

||

Answers:

dict.update() is an operation which has no return type.

Answered By: Serial Lazer

Well, .update() does the dictionary update in place and returns nothing, so when you are initiaising an empty dictionary and updating it, it returns Nothing and None gets assigned to the d2. Instead it will be like:

d = {}
d.update({'p': 'P'})
print(d)
Answered By: Wasif
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.