Python's Dictionary {}

Source: Internet
Author: User

The Python dictionary belongs to a data type, and we can store the data in a dictionary, which is defined using curly braces "{}".
For example, now to store a person's information and then read it, you can use a slice of the way to reflect:

In [1]: info =‘Tom 180 Male‘In [2]: info[1:3]Out[2]: ‘om‘In [3]: info[0:3]Out[3]: ‘Tom‘

So what if we want to save a lot of people's information?

Perhaps we can put the information individually in a single list, and then merge them, but in a way that is very cumbersome in the case of large amounts of data, as shown below:

In [4]: list1=[‘name‘,‘age‘]In [5]: list2=[‘tom‘,‘20‘]In [6]: list3=[‘mike‘,‘24‘]In [7]: zip(list1,list2)Out[7]: [(‘name‘, ‘tom‘), (‘age‘, ‘20‘)]In [8]: list1Out[8]: [‘name‘, ‘age‘]In [9]: list2Out[9]: [‘tom‘, ‘20‘]In [10]: zip(list1,list3)Out[10]: [(‘name‘, ‘mike‘), (‘age‘, ‘24‘)]

A dictionary is the only mapping type (hash table) in Python whose objects are mutable, but the keys of the dictionary must use immutable objects, and a dictionary can use different types of key values, as follows:
Keys ()
VALUES ()
Items ();

First we can create an empty dictionary:

In [11]: dict={}In [12]: type(dict)Out[12]: dict

Define the data as follows:

In [13]: dict={‘a‘:1,1:123}In [14]: dictOut[14]: {1: 123, ‘a‘: 1}                #顺序是可变的,因为遵循哈希表

The data type that is stored in the dictionary should be read-only and the result of the hash should remain the same:

In [15]: dict1={‘a‘:1, 1:123, (‘qq‘,‘wx‘):‘hello‘}In [16]: dict1Out[16]: {1: 123, ‘a‘: 1, (‘qq‘, ‘wx‘): ‘hello‘}

Looking at the length of the dictionary, you can see that the dictionary we just defined has 3 elements:

In [17]: len(dict1)Out[17]: 3

Using the TAB key in Ipython we can see how many ways the dictionary has

In [18]: dict.dict.clear       dict.has_key     dict.itervalues  dict.setdefault  dict.viewkeysdict.copy        dict.items       dict.keys        dict.update      dict.viewvaluesdict.fromkeys    dict.iteritems   dict.pop         dict.values      dict.get         dict.iterkeys    dict.popitem     dict.viewitems   

To view all keys values:

In [18]: dict1.keys()Out[18]: [‘a‘, 1, (‘qq‘, ‘wx‘)]

By looking at all values, you will also return a list of all values stored in the dictionary:

In [19]: dict1.values()Out[19]: [1, 123, ‘hello‘]

Use the keys value to find values:

In [16]: dict1Out[16]: {1: 123, ‘a‘: 1, (‘qq‘, ‘wx‘): ‘hello‘}In [22]: dict1.get(1)Out[22]: 123

If the keys value is not in the dictionary being taken, the value is not returned, but given the keys,values, the values are returned:

In [24]: dict1.get(‘b‘)In [25]: dict1.get(‘b‘,‘c‘)Out[25]: ‘c‘

Determine if keys exist in the dictionary:

In [26]: ‘v‘ in dict1Out[26]: FalseIn [27]: ‘a‘ in dict1Out[27]: True

Or it can be judged as:

In [28]: dict1.has_key(‘v‘)Out[28]: FalseIn [29]: dict1.has_key(‘a‘)Out[29]: True

You can use items to return a dictionary as a list, and then you can iterate over it, or slice it, and get the result you want:

In [16]: dict1Out[16]: {1: 123, ‘a‘: 1, (‘qq‘, ‘wx‘): ‘hello‘}In [30]: dict1.items()Out[30]: [(‘a‘, 1), (1, 123), ((‘qq‘, ‘wx‘), ‘hello‘)]

Update the contents of the dictionary, or update the two dictionaries into a dictionary:

In [35]: dict1Out[35]: {1: 123, ‘a‘: 1, (‘qq‘, ‘wx‘): ‘hello‘}In [36]: dict2Out[36]: {‘e‘: 3, ‘q‘: 1, ‘w‘: 2}In [37]: dict.update(dict1,**dict2)In [38]: dictOut[38]: {1: 123, ‘a‘: 1, ‘e‘: 3, ‘q‘: 1, ‘w‘: 2, (‘qq‘, ‘wx‘): ‘hello‘}

Use the For loop to output the dictionary keys and values:

In [47]: for k in dict1:   ....:     print k,dict1[k]   ....:     a 11 123(‘qq‘, ‘wx‘) hello

Or use items to have the dictionary return a list, and for loop:

In [50]: dict1.items()Out[50]: [(‘a‘, 1), (1, 123), ((‘qq‘, ‘wx‘), ‘hello‘)]In [51]: for k, v in dict1.items(): print k,va 11 123(‘qq‘, ‘wx‘) hello

Dictionary Exercises

#!/usr/local/python3/bin/pythoninfo={}name=input("Please input a number : ")age=input("Please input your age : ")sex=input("Please input your sex(M/F) : ")info[‘name‘]=name  #下标为name的存到info字典里面info[‘age‘]=ageinfo[‘sex‘]=sex#print(info)#print(info.items())for i,w in info.items():    print(‘%s : %s‘ % (i,w))

The operating conditions are as follows:

Please input a number : zyyPlease input your age : 21Please input your sex(M/F) : Fname : zyyage : 21sex : F

Python's Dictionary {}

Related Article

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.