Python字典和结构化数据

字典数据类型

>>> mycat = {'size':'fat','color':'gray','disposition':'loud'}
>>> mycat
{'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
>>> mycat['size']
'fat'
>>> spam = {123:'hello',456:'word'}
>>> spam
{123: 'hello', 456: 'word'}
>>> spam[123]
'hello'

字典与列表

字典的相等不考虑元素的位置,而列表必须位置一致

>>> spam1 = {123:'hello',456:'word'}
>>> spam2 = {456:'word',123:'hello'}
>>> spam1 == spam2
True
>>> spam1 = [1,2,3]
>>> spam2 = [3,2,1]
>>> spam1 == spam2
False

字典的动态查询与添加

birthdays = {}
while True:
    name = input()
    if name == '':
        break
    if name in birthdays:
        print(birthdays[name] + ' is the birthday of ' + name)
    else:
        print('I do not have birthday information of ' + name)
        print('What is their birthday')
        birthday = input()
        birthdays[name] = birthday
        print('Birthday database updated.')
for i in birthdays:
    print(i +' 的生日在 '+birthdays[i])
print(birthdays)

keys()、values()和items()方法

>>> spam = {'color': 'red', 'age': '10'}
>>> for i in spam:
...     print('key = ' + i + ', value = ' + spam[i])
...
key = color, value = red
key = age, value = 10
>>>

直接写 for i in spam 固然简单,但当遇到value的字符类型不一样的时候,就会报错

>>> spam = {'color': 'red', 'age': 10}
>>> for i in spam:
...     print('key = ' + i + ', value = ' + spam[i])
...
key = color, value = red
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>

使用 spam.keys() 可以遍历字典中的key

>>> for i in spam.keys():
...     print(i)
...
color
age

使用 spam.values() 可以遍历字典中的value

>>> for i in spam.values():
...     print(i)
...
red
10

使用 spam.items() 可以遍历字典中的(key, value)

>>> for i in spam.items():
...     print(i)
...
('color', 'red')
('age', 10)

与列表转换

>>> spam
{'color': 'red', 'age': 10}
>>> spam.keys()
['color', 'age']
>>> list(spam.keys())
['color', 'age']
>>> spam.items()
[('color', 'red'), ('age', 10)]
>>> spam.values()
['red', 10]
>>>

检查字典中是否存在键或值

>>> spam
{'color': 'red', 'age': 10}
>>> 'name' in spam.keys()
False
>>> 'color' in spam.keys()
True
>>> 'red' in spam.values()
True

get()方法

#使用get()
>>> temp = {'apple': 5, 'banana': 6}
>>> 'I am bringing ' + str(temp.get('apple',0)) + ' apple'
'I am bringing 5 apple'
>>> 'I am bringing ' + str(temp.get('eggs',0)) + ' eggs'
'I am bringing 0 eggs'
>>> temp
{'apple': 5, 'banana': 6}

#未使用get()
>>> 'I am bringing ' + str(temp['apple']) + ' apples'
'I am bringing 5 apples'
>>> 'I am bringing ' + str(temp['eggs']) + ' eggs'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'eggs'

setdefault()方法

在字典中为某个键值设置一个默认值,当该键没有任何值使用时,默认值生效

>>> spam
{'color': 'red', 'age': 10}
>>> spam.setdefault('name', 'Tom')
'Tom'
>>> spam
{'color': 'red', 'age': 10, 'name': 'Tom'}
>>> spam.setdefault('name', 'Joy')
'Tom'
>>> spam
{'color': 'red', 'age': 10, 'name': 'Tom'}
>>> spam['name'] = 'Lili'
>>> spam
{'color': 'red', 'age': 10, 'name': 'Lili'}

漂亮打印

import pprint

temp = 'Yes, I can do it.'
count = {}
for i in temp:
    count.setdefault(i, 0)
    count[i] = count[i] + 1
pprint.pprint(count)
{' ': 4,
 ',': 1,
 '.': 1,
 'I': 1,
 'Y': 1,
 'a': 1,
 'c': 1,
 'd': 1,
 'e': 1,
 'i': 1,
 'n': 1,
 'o': 1,
 's': 1,
 't': 1}

使用数据结构对真实世界建模

  • 井字棋盘
# -*- coding: utf-8 -*-

tboard = {'T-L': ' ', 'T-C': ' ', 'T-R': ' ',
          'M-L': ' ', 'M-C': ' ', 'M-R': ' ',
          'B-L': ' ', 'B-C': ' ', 'B-R': ' '}

'''
tboard = {}
for a in ['T','M','B']:
    for b in ['L','C','R']:
        tboard.setdefault(a + '-' + b, ' ')
'''

def func(board):
    print(board['T-L'] + '|' + board['T-C'] + '|' + board['T-R'])
    print(board['M-L'] + '|' + board['M-C'] + '|' + board['M-R'])
    print(board['B-L'] + '|' + board['B-C'] + '|' + board['B-R'])

turn = 'X'
for i in range(9):
    func(tboard)
    print(u'请 ' + turn + u' 选定位置')
    temp = input()  # 输入"T-L" 等
    tboard[temp] = turn
    if turn == 'X':
        turn = 'O'
    else:
        turn = 'X'

嵌套字典和列表

all = {'Tom':{'Apple':4, 'Egg':3},
       'Lili':{'Banana':2, 'Apple':2},
       'Joy':{'Orange':3, 'Egg':2}
    }
def totalBrought(temp, item):#指定查询
    num = 0
    for v in temp.values():
        num = num + v.get(item, 0)
    return num

def func(temp): #全部查询
    for v in temp.values():
        for a in v.keys():
            t.setdefault(a, 0)
            t[a] = t[a] + v[a]
t = {}
func(all)
for k,v in t.items():
    print('统一查询:' + k + ' = ' + str(v))
print()
print('指定查询:Apple = ' + str(totalBrought(all, 'Apple')))

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/22/python-dictionary-and-structured-data/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Python字典和结构化数据
字典数据类型 >>> mycat = {'size':'fat','color':'gray','disposition':'loud'} >>&……
<<上一篇
下一篇>>
文章目录
关闭
目 录