Home Backend Development Python Tutorial Python's dict dictionary structure operation method

Python's dict dictionary structure operation method

Mar 02, 2017 pm 05:15 PM
dict python dictionary

This article mainly introduces the operation method of Python's dict dictionary structure. Learning notebook. The operation of dictionary is the basic knowledge for introductory learning of Python. Friends who need it can refer to

1. Dictionary Basic method

1. Create a new dictionary

1) Create an empty dictionary

1

2

3

4

>>> dict1={}

>>> dict2=dict()

>>> dict1,dict2

({}, {})

Copy after login

2), initialize a value when creating a new one

1

2

3

>>> dict1={1:'a',2:'b',3:'c'}

>>> dict1

{1: 'a', 2: 'b', 3: 'c'}

Copy after login

3), use tuple


1

2

3

>>> dict1=dict([(1,'a'),(2,'b'),(3,'c')])

>>> dict1

{1: 'a', 2: 'b', 3: 'c'}

Copy after login

2. Obtaining method

1), get(key) Get the value corresponding to a key from the dictionary and return value


1

2

3

>>> dict1={1:'a',2:'b',3:'c'}

>>> dict1.get(1)

'a'

Copy after login

If it does not exist in the dictionary, return a NoneType

1

2

>>> type(dict1.get(4))

<type &#39;NoneType&#39;>

Copy after login

If the required key value does not exist, specify another value to return

1

2

>>> dict1.get(4,&#39;not found&#39;)

&#39;not found&#39;

Copy after login

2), keys () Get all the key values ​​​​in the dictionary and return a list

1

2

>>> dict1.keys()

[1, 2, 3]

Copy after login

3), values() corresponds to the keys() method, and returns the keys in the dictionary List of all values

1

2

>>> dict1.values()

[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

Copy after login

4), items() returns a tuple corresponding to (key, value)

1

2

>>> dict1.items()

[(1, &#39;a&#39;), (2, &#39;b&#39;), (3, &#39;c&#39;)]

Copy after login

5), iterkeys(), itervalues(), iteritems() also obtain all key, value, (key, value) ancestors respectively, but they no longer return a list, but an iterator

1

2

3

4

5

>>> for key in dict1.iterkeys():

 print key

1

2

3

Copy after login


3. Method of setting dictionary value

1) The direct method is


1

2

3

>>> dict1[4]=&#39;d&#39;

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;, 4: &#39;d&#39;}

Copy after login

However, this method is that if the key value I want to add is already in the dictionary, then the original one will be overwritten. The value

1

2

3

>>> dict1[4]=&#39;e&#39;

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;, 4: &#39;e&#39;}

Copy after login

2), setdefault(key, value) The advantage of this method is that if the inserted key does not exist in the dictionary, then insert it into the dictionary and Return the value. Otherwise, if it exists in the dictionary, then the existing value will be returned and will not be overwritten.

1

2

3

4

5

6

7

8

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;, 4: &#39;e&#39;}

>>> dict1.setdefault(5,&#39;f&#39;)

&#39;f&#39;

>>> dict1.setdefault(5,&#39;g&#39;)

&#39;f&#39;

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;, 4: &#39;e&#39;, 5: &#39;f&#39;}

Copy after login

4. Delete the dictionary

1) pop(key) deletes an item of the specified key and successfully returns the value of the deleted item. If it does not exist, an exception will be thrown. Therefore, when using this method, you must judge whether the key is Exists, or catch this exception

1

2

3

4

5

6

7

8

9

10

>>> def pop_key(d,key):

 try:

 d.pop(key)

 print "sucess"

 except:

 print "key is not in dict"

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;}

>>> pop_key(dict1,3)

key is not in dict

Copy after login


## or

1

2

3

4

5

6

7

8

>>> def sub_dict2(d,key):

 if d.has_key(key):

 d.pop(key)

 print "sucess"

 else:print "key is not in dict"

  

>>> pop_key(dict1,3)

key is not in dict

Copy after login

The has_key (key) here is to determine whether the key is in the dictionary. Of course, you can also use key in d instead

2) popitem() is similar to pop(), except that it deletes A (key, value) tuple

Using the above method, you can use some advanced usage

A. We create a dictionary through 2 lists, the first list are all the keys, and the second list is all the values

1

2

3

4

5

>>> list1=[1,2,3]

>>> list2=[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]

>>> dict1=dict(zip(list1,list2))

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;}

Copy after login


B. Find the child of a dictionary Dictionary

1

2

3

4

5

6

7

8

9

10

11

>>> dict1

{1: 'a', 2: 'b', 3: 'c'}

>>> dict1=dict([(1,&#39;a&#39;),(2,&#39;b&#39;),(3,&#39;c&#39;)])

>>> dict1

{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;}

>>> subkeys=[1,3]

>>> def sub_dict(d,subkeys):

 return dict([(k,d.get(k)) for k in subkeys if k in d])

  

>>> print sub_dict(dict1,subkeys)

{1: 'a', 3: 'c'}

Copy after login

C. Reverse the dictionary, that is, the key becomes the value of the new dictionary, and the value becomes the key of the new dictionary (note that if the value has Repeat, the reversed dictionary will only retain one

1

2

3

4

5

6

>>> def invert_dict(d):

 return dict([(k,v) for v,k in d.iteritems()])

  

>>> print invert_dict(dict1)

{&#39;a&#39;: 1, &#39;c&#39;: 3, &#39;b&#39;: 2}

>>>

Copy after login

##5. Other basic methods

1 ) has_key(key) Determine whether the key is in the dictionary

2) copy() returns a copy of the dictionary (the copy is a shallow copy)

1

2

3

4

5

>>> d2={1:[1],2:[2],3:[3]}

>>> d3=d2.copy()

>>> d3[1].append(4)

>>> d2[1]

[1, 4]

Copy after login

If you want to deep copy, you need to use copy.deepcopy(a)

1

2

3

4

5

6

>>> d2={1:[1],2:[2],3:[3]}

>>> import copy

>>> d3=copy.deepcopy(d2)

>>> d3[1].append(4)

>>> print d2[1] , d3[1]

[1] [1, 4]

Copy after login

3) clear() clear dict

4) update(d) uses one dictionary to update another dictionary, which is somewhat similar to merging two dictionaries

1

2

3

4

5

6

>>> dict1={1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;}

>>> dict2={1:&#39;x&#39;,4:&#39;y&#39;}

>>> dict1.update(dict2)

>>> dict1

{1: &#39;x&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;, 4: &#39;y&#39;}

>>>

Copy after login

2. Traversing

There are many ways to traverse a dictionary

1. Directly use dict

1

2

3

4

5

6

7

8

>>> d

{&#39;a&#39;: &#39;aa&#39;, &#39;c&#39;: &#39;cc&#39;, &#39;b&#39;: &#39;bb&#39;}

>>> for i in d:

 print i,d[i]

  

a aa

c cc

b bb

Copy after login

2. Use items()

1

2

3

4

5

6

>>> for i,v in d.items():

 print i,v

  

a aa

c cc

b bb

Copy after login

##Of course you can also do this

1

2

3

4

5

6

>>> for (i,v) in d.items():

 print i,v

  

a aa

c cc

b bb

Copy after login

I remember that there was an article comparing the efficiency of these two methods (with brackets and without brackets). It said that when the dictionary size is below 200, brackets are faster. When it is above 200, the speed without brackets is a little faster, but I have not tested it specifically.

3. iteritems()

(I think it’s a better method)

1

2

3

4

5

6

>>> for k,v in d.iteritems():

 print k,v

  

a aa

c cc

b bb

Copy after login

There are others Traversal methods, but I feel that these 3 are enough

3. Some advanced usage


1. One-click multi-value

Generally, dictionaries are mapped one-to-one, but if we need one-to-many mapping, such as a book, we need to count the number of pages where some words appear. Then, you can use list as the value of dict. This can be accomplished by using the setdefault() method


1

2

3

4

5

6

7

8

9

10

>>> d={&#39;hello&#39;:[1,4,9],"good":[1,3,6]}

>>> d

{&#39;good&#39;: [1, 3, 6], &#39;hello&#39;: [1, 4, 9]}

>>> d.setdefault(&#39;good&#39;,[]).append(7)

>>> d

{&#39;good&#39;: [1, 3, 6, 7], &#39;hello&#39;: [1, 4, 9]}

>>> d.setdefault(&#39;bad&#39;,[]).append(2)

>>> d

{&#39;bad&#39;: [2], &#39;good&#39;: [1, 3, 6, 7], &#39;hello&#39;: [1, 4, 9]}

>>>

Copy after login

当然,如果写成一个函数话,就可以更方便的使用,
我们也可以利用set来代替list


1

2

3

4

5

6

7

8

9

>>> def addFunc(d,word,pag):

 d.setdefault(word,set()).add(pag)

>>> d={&#39;hello&#39;:set([1,4,9]),"good":set([1,3,6])}

>>> addFunc(d,&#39;hello&#39;,8)

>>> d

{&#39;good&#39;: set([1, 3, 6]), &#39;hello&#39;: set([8, 1, 4, 9])}

>>> addFunc(d,&#39;bad&#39;,8)

>>> d

{&#39;bad&#39;: set([8]), &#39;good&#39;: set([1, 3, 6]), &#39;hello&#39;: set([8, 1, 4, 9])}

Copy after login

2、利用字典完成简单工厂模式
字典的value不单单只是一些常见的字符串,数值,还可以是类和方法,比如我们就可以这样来实现简单工厂模式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

>>> class cat(object):

 def __init__(self):

 print &#39;cat init&#39;

>>> class dog(object):

 def __init__(self):

 print &#39;dag init&#39;

>>> d={&#39;cat&#39;:cat,&#39;dog&#39;:dog}

>>> def factoryFunc(d,name):

 if name in d:

 return d[name]()

 else:

 raise Exception("error")

>>> cat=factoryFunc(d,&#39;cat&#39;)

cat init

Copy after login

另外一个例子,利用变量来控制执行的函数

1

2

3

4

5

6

7

8

9

10

>>> def deal_cat():

 print &#39;cat run!!&#39;

  

>>> def deal_dog():

 print &#39;dag run!!&#39;

  

>>> d={&#39;cat&#39;:deal_cat ,&#39;dog&#39;:deal_dog }

>>> animal=&#39;cat&#39;

>>> d[animal]()

cat run!!

Copy after login


更多Python的dict字典结构操作方法相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Can Python parameter annotations use strings? Can Python parameter annotations use strings? Apr 01, 2025 pm 08:39 PM

Alternative usage of Python parameter annotations In Python programming, parameter annotations are a very useful function that can help developers better understand and use functions...

How do Python scripts clear output to cursor position at a specific location? How do Python scripts clear output to cursor position at a specific location? Apr 01, 2025 pm 11:30 PM

How do Python scripts clear output to cursor position at a specific location? When writing Python scripts, it is common to clear the previous output to the cursor position...

Why can't my code get the data returned by the API? How to solve this problem? Why can't my code get the data returned by the API? How to solve this problem? Apr 01, 2025 pm 08:09 PM

Why can't my code get the data returned by the API? In programming, we often encounter the problem of returning null values ​​when API calls, which is not only confusing...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to use Go or Rust to call Python scripts to achieve true parallel execution? How to use Go or Rust to call Python scripts to achieve true parallel execution? Apr 01, 2025 pm 11:39 PM

How to use Go or Rust to call Python scripts to achieve true parallel execution? Recently I've been using Python...

Where to download Python .whl files under Windows? Where to download Python .whl files under Windows? Apr 01, 2025 pm 08:18 PM

Python binary library (.whl) download method explores the difficulties many Python developers encounter when installing certain libraries on Windows systems. A common solution...

See all articles