Python dictionary introduction and Usage Details

Source: Internet
Author: User
Tags print format

Python dictionary introduction and Usage Details

#!/usr/bin/env python# -*- coding:utf-8 -*-"""

Old Rules: Environment 2.7.x in the following method. Please remember the print format (the output content should be placed in parentheses) for users of version 3.x or later)

Basic composition and usage of dictionaries

dict = { key : value }dict[ key ] = value

First, the dictionary is a basic structure composed of key keys and value values.

The key cannot be named by multiple elements such as list and dict dictionary,

The key is a unique attribute and can be called a one-to-one service. The key is the same but only one

The value can be named by one or more elements. It is not a unique attribute and can be called a one-to-many service.

The most important thing is that the dictionary is unordered.

Let's take a look at the usage of the dictionary:

"# Dic ={} initializes a dictionary dic_samekey = {" a ": None," a ": None," B ": None," B ": none} # print dic_samekeydic_morevalue = {"a": ["0", "1", "2"], "B": {"c": 0, "d": 1, "e": 2}, "t" :( 0, 1, 2 )} # print dic_morevalue # It is a headache to see multiple values at this time. How can we get them? # In fact, the value I named has been marked with a subscript and is also sorted by default, remind me again when the dictionary is unordered # dict [key] = value so that you can name a dictionary and get the desired value print dic_morevalue ["a"] [0], dic_morevalue ["a"] [1], dic_morevalue ["a"] [2] print dic_morevalue ["B"] ["C"], dic_morevalue ["B"] ["d"], dic_morevalue ["B"] ["e"] # multi-dictionary usage can be used to construct a multi-level selection print dic_morevalue ["t"] [0], dic_morevalue ["t"] [1], dic_morevalue ["t"] [2] # quickly obtain all the key methods and types of dictionary print dic_morevalue.keys (), type (dic_morevalue.keys ()) # The returned type is the list # quickly obtain all the value methods and types of the dictionary print dic_morevalue.values (), type (dic_morevalue.values () # It is also the list # copy as the name implies (shallow copy) commonly known as the value dic_test = dic_morevalue.copy () dic = dic_testprint dic_test # clear, In this way, print dic_morevalue.clear () # has_key is used to determine whether the key exists in the dictionary. boolean type is returned, that is, True is True, True is True, and false is false. dic_test.has_key ("B ") # get can also be used to determine whether the key is in the dictionary. If no key exists, the default value Noneprint dic_test.get ("k") is returned ") # pop is used to remove a dictionary key and Its valueb = dic_test.pop ("B") print dic_test, u "removed B:", B # item () every pair of key and value in the dictionary is made up of a tuple, and these tuples are put in the list to return. Item = dic_test.items () print item # update combines the two dictionaries into the dictionary where update is used. dic2 = {"j": "nice"} dic_test.update (dic2) print dic_test # fromkeys name the value from the keys key queue in a unified manner. If not set, Noneseq = ["name", "age", "job"] print dic_test.fromkeys (seq) print dic_test.fromkeys (seq, "guess") # name it guess

Next, let's take a look at the usage of the dictionary:

I. Create a dictionary

The dictionary is composed of key pairs and corresponding values. A dictionary is also called an associated array or a hash table. The basic syntax is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can also create a dictionary as follows:

dict1 = { 'abc': 456 };dict2 = { 'abc': 123, 98.6: 37 };

Note:

Each key and value are separated by a colon (:). Each pair is separated by a comma. Each pair is separated by a comma and placed in curly brackets ({}).
The key must be unique, but the value is not required.
Values can be of any data type, but must be immutable, such as strings, numbers, or tuples.

2. Access the value in the dictionary

Place the corresponding keys in the familiar square brackets, as shown in the following example:

#! /Usr/bin/pythondict = {'name': 'zara ', 'age': 7, 'class': 'first'}; print "dict ['name']: ", dict ['name']; print" dict ['age']: ", dict ['age']; # output result of the above instance: # dict ['name']: Zara # dict ['age']: 7

If you use a key that is not in the dictionary to access data, an error is returned as follows:

#! /Usr/bin/pythondict = {'name': 'zara ', 'age': 7, 'class': 'First'}; print "dict ['Alice ']: ", dict ['Alice ']; # output result of the above instance: # dict ['zara']: # Traceback (most recent call last): # File" test. py ", line 4, in <module> # print" dict ['Alice ']: ", dict ['Alice']; # KeyError: 'Alice '[/code]

3. Modify the dictionary

You can add a new key/value pair to a dictionary to modify or delete an existing key/value pair as follows:

#! /Usr/bin/pythondict = {'name': 'zara ', 'age': 7, 'class': 'first'}; dict ['age'] = 8; # update existing entrydict ['school '] = "DPS School"; # Add new entryprint "dict ['age']:", dict ['age']; print "dict ['school ']:", dict ['school']; # output result of the above instance: # dict ['age']: 8 # dict ['school ']: DPS School

4. Delete dictionary elements

Only one operation is required to delete a single element and clear the dictionary.

The following example shows how to delete a dictionary using the del command:

#! /Usr/bin/pythondict = {'name': 'zara ', 'age': 7, 'class': 'first'}; del dict ['name']; # Delete the dict entry whose key is 'name. clear (); # clear all dictionary entries del dict; # Delete the dictionary print "dict ['age']:", dict ['age']; print "dict ['school ']:", dict ['school']; # This raises an exception because the dictionary after del does not exist: dict ['age']: # Traceback (most recent call last): # File "test. py ", line 8, in <module> # print" dict ['age']: ", dict ['age']; # TypeError: 'type' object is unsubscriptable

V. Features of dictionary keys

Dictionary values can be any python object without restrictions. They can be either standard objects or user-defined objects, but cannot be keys.

There are two important points to remember:

1) the same key cannot appear twice. If the same key is assigned twice during creation, the last value will be remembered as follows:

#! /Usr/bin/pythondict = {'name': 'zara ', 'age': 7, 'name': 'manni'}; print "dict ['name']: ", dict ['name']; # output result of the above instance: # dict ['name']: Manni

2) The key must be unchangeable. Therefore, you can use numbers, strings, or tuples to act as the key. Therefore, you cannot use the list, as shown in the following example:

#! /Usr/bin/pythondict = {['name']: 'zara ', 'age': 7}; print "dict ['name']:", dict ['name']; # output result of the above instance: # Traceback (most recent call last): # File "test. py ", line 3, in <module> # dict = {['name']: 'zara ', 'age': 7}; # TypeError: list objects are unhashable

6. built-in dictionary Functions & Methods

The Python dictionary contains the following built-in functions:

1,cmp(dict1, dict2):Compares two dictionary elements.
2,len(dict):Calculate the number of dictionary elements, that is, the total number of keys.
3,str(dict):Output dictionary printable string representation.
4,type(variable):Return the input variable type. If the variable is a dictionary, the dictionary type is returned.

The Python dictionary contains the following built-in methods:

1,radiansdict.clear():Delete all elements in the dictionary
2,radiansdict.copy():Returns the shortest copy of a dictionary.
3,radiansdict.fromkeys():Create a new dictionary and use the elements in sequence seq as the dictionary key. val is the initial value corresponding to all the keys in the dictionary.
4,radiansdict.get(key, default=None):Returns the value of the specified key. If the value is not in the dictionary, the default value is returned.
5,radiansdict.has_key(key):If the key returns true in the dictionary dict, otherwise false is returned.
6,radiansdict.items():Returns a list of traversal (Key, value) tuples.
7,radiansdict.keys():Returns all keys of a dictionary in a list.
8,radiansdict.setdefault(key, default=None):Similar to get (), but if the key does not exist in the dictionary, a key is added and the value is set to default.
9,radiansdict.update(dict2):Update the dictionary dict2 key/value pairs to dict.
10,radiansdict.values():Returns all values in the dictionary as a list.

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.