SoFunction
Updated on 2024-11-16

python's method of constructing a dictionary by means of dict (zip) and {}

In python, this is usually done through thedictcap (a poem)zipcombinations to build key-value pairs.

For example:

aid = [i for i in range(10)]
name = [[1] * 3] * len(aid)
dic1 = dict(zip(aid,name))
print('dic1:', dic1)

Get:

{0: [1, 1, 1],
1: [1, 1, 1],
2: [1, 1, 1],
3: [1, 1, 1],
4: [1, 1, 1],
5: [1, 1, 1],
6: [1, 1, 1],
7: [1, 1, 1],
8: [1, 1, 1],
9: [1, 1, 1]}

This establishes theaidcap (a poem)nameof the one-to-one mapping relationship, using the aid as the key and the second column as the value.

It can also be accessed through thedicfunction of the form or{}direct construction

dic2 = {'aid': aid,'name':name}
print('\ndic2:',dic2)

{
‘aid’: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
‘name’: [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
}

This way by creating a new key, the list is stored as a value.

The above two methods, if you want to go through the aids for indexing to get the corresponding value:

Method 1 can be taken out directly, method 2 still need to get to the index and then take the value. So method 1 is faster but in contrast, method 1 stores many key-value pairs, which is not as good as method 2 in terms of storage space.

The space occupancy tests are as follows:

aid = [i for i in range(10)]
name = [[1] * 3] * len(aid)

dic1 = dict(zip(aid,name))
dic2 = {'aid': aid,'name':name}
print('dic1:', dic1)
print((dic1))

print('\ndic2:',dic2)
print((dic2))
dic1: {0: [1, 1, 1], 1: [1, 1, 1], 2: [1, 1, 1], 3: [1, 1, 1], 4: [1, 1, 1], 5: [1, 1, 1], 6: [1, 1, 1], 7: [1, 1, 1], 8: [1, 1, 1], 9: [1, 1, 1]}
360

dic2: {'aid': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'name': [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]}
232

After testing, the dictionary footprint and the number of key-value pairs are not linear. If in a very large data, you need to consider the size of the occupied space, for example. 10000 key-value pairs, occupied 7w bytes. (Applied in saving embeddings offline)

to this article on python by way of dict (zip) and {} to construct the dictionary of the article is introduced to this, more related python dict construct dictionary content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!