Python implements methods for creating dictionaries without too many references

  • 2020-04-02 14:07:06
  • OfStack

This article illustrates how a python implementation can create a dictionary without too many references. Share with you for your reference. The specific implementation method is as follows:

1. Use the itertools module


import itertools
the_key = ['ab','22',33]
the_vale = ['aaaa',"dddddddd",'22222222222']
d = dict(itertools.izip(the_key,the_vale))
print d

2. Add parameters


dict = dict(red = 1,bule = 2,yellow = 3)
print dict

Result: {'yellow': 3, 'bule': 2, 'red': 1}

Use the built-in zip function
Zip ([iterable,... ) returns a list,


the_key = ['ab','22',33]
the_vale = ['aaaa',"dddddddd",'22222222222']
dict2 = dict(zip(the_key,the_vale))
print type(zip(the_key,the_vale))
print dict2

Results:


<type 'list'>
{33: '22222222222', 'ab': 'aaaa', '22': 'dddddddd'}

4. The fromkeys function of dict
Each key created has the same value


fromkeys(seq[,value])
Create a new dictionary with keys from seq and values set to value.

the_key = ['ab','22',33]
the_vale = 0
d = dict.fromkeys(the_key,the_vale)
print 

Result: {33: 0, 'ab': 0, '22': 0}


import string
count_by_letter = dict.fromkeys(string.ascii_lowercase,0)
print count_by_letter

Results:


{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}

I hope that this article has helped you to learn Python programming.


Related articles: