Python implements a way to create a dictionary without having to invoke it too much _python

Source: Internet
Author: User

This article illustrates the Python implementation method of creating a dictionary without having to invoke it too much. Share to everyone for your reference. The implementation methods are as follows:

1. Using the Itertools module

Import itertools
the_key = [' ab ', ', ']
the_vale = [' aaaa ', ' dddddddd ', ' 22222222222 ']
d = dict ( Itertools.izip (The_key,the_vale))
print D

2. Add parameter

Dict = dict (red = 1,bule = 2,yellow = 3)
Print Dict

The result is: {' Yellow ': 3, ' Bule ': 2, ' Red ': 1}

3. Use the built-in zip function
Zip ([iterable,...]) Returns a list of

The_key = [' ab ', ', ']
the_vale = [' aaaa ', ' dddddddd ', ' 22222222222 ']
dict2 = dict (Zip (The_key,the_vale))
Print type (Zip (the_key,the_vale))
print Dict2

Results:

<type ' list ' >
{: ' 22222222222 ', ' ab ': ' AAAA ', ': ' DDDDDDDD '}

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

Fromkeys (Seq[,value])
Create A new dictionary with the keys from SEQ and values set to value.

The_key = [' ab ', ', ']
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 this article will help you with your study of Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.