S
S
skymike2018-06-19 02:23:05
Python
skymike, 2018-06-19 02:23:05

How to understand the behavior of a dictionary?

There is a dictionary created manually

dch = {0:'0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9'}

and the dictionary created by the generator eventually has two identical dictionaries containing string values
dch2 = {x: str(x) for x in range(10)}
>>> type(dch)
<class 'dict'>
>>> type(dch2)
<class 'dict'>
>>> type(dch[5])
<class 'str'>
>>> type(dch2[5])
<class 'str'>
>>> dch[5]
'5'
>>> dch2[5]
'5'

but one thing, but if you make a comparison with a value from a manually made dictionary, then everything works, True is returned, but if you compare it with a dictionary from a False generator, although the values ​​\u200b\u200bconverge
>>> dch[5] is '5'
True
>>> dch2[5] is '5'
False

Why is that? after all, the dictionaries are the same and the values ​​​​in them are of the same, string type, and are compared with a string.
And if you add a string value to the generated dictionary manually, then it passes the comparison correctly, the rest of the values ​​that are not from the generator.
>>> dch2[10] = '10'
>>> dch2[10] is '10'
True
>>> dch2[9] is '9'
False
>>>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-06-19
@immaculate

As sim3x wrote, isit checks for equality not of a value, but of a reference. You can get the same behavior even with integers: https://stackoverflow.com/questions/15171695/whats...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question