The python dict dictionary and some examples of assignment references of in detail

  • 2020-05-24 05:46:15
  • OfStack

Recently, I have been working on a large database, which needs to be searched according to the value. Therefore, I thought of the dictionary in python. I haven't used dict at ordinary times

The most used ones are list and tuple.

Here's how to create a dictionary:

Method 1:

dict = {'name': 'earth', 'port': 80}


Method 2:

fdict = dict((['x', 1], ['y', 2]))


Method 3:

ddict = {}.fromkeys(('x', 'y'), -1)


I have experimented with these methods for 1, and found that they are not working well, and I cannot get the results I want, because the result found by the database is of type tuple, which cannot be changed. With method 2, I have to make sure that it is inside

It's list (in this case, tuple and list, the interchangeable method l=tuple(l) l = list(l))

When I was doing the exercise, I suddenly saw one method, so I'm going to declare one

fdict= {}

then

fdict[keys] = values

And then I'm going to loop through this, and I'm going to add one by one to the fdict, and it's not going to be overwritten, because I thought it was going to be overwritten by default

In this way, 1 turns the result into a key-value pair

The transmitted value in python is actually the address:

Example:

a = [1,2,3,4]

b = a

a.append(1)

print a

print b


The results show that both results are: [1,2,3,4,1]

This means that when one variable in python assigns a value to another variable, the address is passed, so when the value pointed to by a changes, b will get a pointer to a, so the result will also be

The output result is the same as a


more experiments:

a = [1,2,3,4]

b = a

a += [1] # adds an list value to the tail

print a

print b


It can be seen that the result is:

[1, 2, 3, 4, 1]


[1, 2, 3, 4, 1]

There is no problem with this, or as explained in 1 above, the address is transmitted. No matter how a is added, b is the same output as a address


Here's another experiment:


a = [1,2,3,4]

b = a

a = a + [1] # add 1 list value at the end

print a

print b

Readers can try running 1 to see the results


The result of operation is:

[1,2,3,4,1]

[1,2,3,4]


Why is that?

Why is plus PI equals PI and plus PI separately added to each other


By looking up the information, I am convinced of the following explanation:

When a = a+[1], what the system does is put the result of a +[1] into another address, c, and then point a to the c address, so when you print a, the result is predictable

However, b still points to the same position as a before, and the value of the previous position has not changed, so b will output such a somewhat surprising value

And the += operation will still operate at the address pointed to by a, so b will also change accordingly


Conclusion: in python, when one variable assigns a value to another variable (=), it is not the value that is passed, but the pointer address


Related articles: