Learn Python dict every day

Source: Internet
Author: User

Learn Python dict every day
Learn Python dict every day

The dictionary is used to store key-value pairs. Keys and values in the same dictionary in Python can be of different types.

Create a dictionary

There are two ways to create an empty dictionary:

d = {}d = dict()

There are many dictionary methods for creating an element. The following operation results are the same:

>>> a = dict(one=1, two=2, three=3)>>> b = {'one': 1, 'two': 2, 'three': 3}>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))>>> d = dict([('two', 2), ('one', 1), ('three', 3)])>>> e = dict({'three': 3, 'one': 1, 'two': 2})
Dictionary Query

You only need to use dict [key] to obtain the value in the dictionary. If this key does not exist, a KeyError error is thrown. It is also available.dict.get(k[,default])This method does not throw an error even if the key does not exist. You can also give a default value to return if the key-Value Pair does not exist:

>>> a = dict(one=1, two=2, three=3)>>> a['one']1>>> a['four']Traceback (most recent call last):  File "", line 1, in 
  
   KeyError: 'four'>>> a.get('four')>>> a.get('four',4)4
  
Dictionary Modification

To modify the value corresponding to the key in the dictionary, you only need to obtain it and assign values to it directly. Note that if the modified key does not exist, it is changed to adding a key-value pair to the dictionary:

>>> a = dict(one=1, two=2, three=3)>>> a['one']=10>>> a{'two': 2, 'one': 10, 'three': 3}>>> a['four']=4>>> a{'two': 2, 'four': 4, 'one': 10, 'three': 3}

Whiledict.setdefault(key[,default])If the key exists, this value is returned without modification. If the key does not exist, a key-Value Pair (key, default) is added. The default value is None:

>>> a = dict(one=1, two=2, three=3)>>> a.setdefault('one')1>>> a{'two': 2, 'one': 1, 'three': 3}>>> a.setdefault('four')>>> a{'two': 2, 'four': None, 'one': 1, 'three': 3}

Batch adddict.update(p)Method.

Delete a dictionary

If you want to delete a key-value pair, you can directly use the del method to try to delete a non-existent key-value pair. A KeyError error is thrown:

>>> a{'two': 2, 'four': 4, 'one': 10, 'three': 3}>>> del a['four']>>> a{'two': 2, 'one': 10, 'three': 3}>>> del a['four']Traceback (most recent call last):  File "", line 1, in 
  
   KeyError: 'four'
  

You can also call dict. clear () to clear the dictionary. Anddict.pop(key[,default])Anddict.popitem()One of the two is the key-value pair corresponding to the pop-up key, and the other is any one of the pop-up key-value pairs:

>>> a{'two': 2, 'one': 10, 'three': 3}>>> a.pop("one")10>>> a{'two': 2, 'three': 3}>>> a.popitem()('two', 2)>>> a{'three': 3}
Dictionary set

The dictionary can return all its key-value pairs, keys, and values respectively. Their types are built-in dictionary types and can be converted to the list through list:

>>> a = dict(one=1, two=2, three=3)>>> a{'two': 2, 'one': 1, 'three': 3}>>> a.items()dict_items([('two', 2), ('one', 1), ('three', 3)])>>> a.values()dict_values([2, 1, 3])>>> a.keys()dict_keys(['two', 'one', 'three'])>>> list(a.keys())['two', 'one', 'three']

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.