创建和使用字典
与列表和元组的区别。共同点:都是通过索引引用元素值;不同点:列表是可读写的,元组是只读的。
names = [ "Bill" , "Mike" , "John" , "Mary" ]
numbers = [ "1234" , "4321" , "6789" , "6543" ]
print ( numbers[ names. index( "Mike" ) ] )
print ( names[ numbers. index( "1234" ) ] )
4321
Bill
phoneBook = { "Bill" : "1234" , "Mike" : "45678" , "Jackson" : "0814" }
print ( phoneBook)
{'Bill': '1234', 'Mike': '45678', 'Jackson': '0814'}
print ( phoneBook[ "Jackson" ] )
0814
使用dict函数将序列转换为字典
items = [ [ 'Bill' , "4321" ] , ( "Mike" , "7891" ) , [ 'John' , '4567' ] ]
d = dict ( items)
print ( d)
{'Bill': '4321', 'Mike': '7891', 'John': '4567'}
dict1 = dict ( name= "Bill" , number= 6543 , age= 34 )
print ( dict1)
{'name': 'Bill', 'number': 6543, 'age': 34}
items = [ ]
while True :
key = input ( "请输入key: " )
if key == ":exit" :
break ;
value = input ( "请输入value:" )
keyValue = [ key, value]
items. append( keyValue)
d = dict ( items)
print ( d)
请输入key: name
请输入value:Mike
请输入key: Salary
请输入value:34
请输入key: location
请输入value:China
请输入key: :exit
{'name': 'Mike', 'Salary': '34', 'location': 'China'}
字典的基本操作
通过len函数获取字典的长度 通过key获取和设置字典中的值 key的类型,列表只能是数字(索引),字典的key可以是多种类型,如字符串、元组等。 自动添加,引用列表元素,索引必须在范围内,否则会抛出异常,字典的key如果不存在,会添加一个key-value对。 查找成员,列表使用in,直接查找值,字典使用in,查找key;查找效率,字典要高于列表和元组。
items = [ 1 , 2 , 3 , 4 , 5 ]
print ( len ( items) )
d = { "name" : "Bill" , "age" : 43 }
print ( len ( d) )
5
2
print ( d[ "name" ] )
Bill
print ( d)
{'name': 'Bill', 'age': 43}
d[ "salary" ] = 5432
print ( d)
{'name': 'Bill', 'age': 43, 'salary': 5432}
print ( 1 in items)
print ( 10 in items)
print ( "name" in d)
print ( "location" not in d)
True
False
True
True
IDEs = {
'eclipse' :
{
'languages' : [ 'Java' , 'Python' , 'JavaScript' , 'PHP' ] ,
'organization' : 'Eclipse基金会'
} ,
'visualstudio' :
{
'languages' : [ 'C#' , 'C++' , 'VB.NET' ] ,
'organization' : '微软'
} ,
'webstorm' :
{
'languages' : [ 'JavaScript' ] ,
'organization' : 'JetBrain'
}
}
labels = {
'languages' : '支持的编程语言' ,
'organization' : '所属机构'
}
IDE = input ( '请输入IDE的名字:' )
findIDE = IDE. replace( " " , "" ) . lower( )
choice = input ( '要查询IDE支持的编程语言(lang)还是所属组织机构(org)?' )
if choice == 'lang' : key = 'languages'
if choice == 'org' : key = 'organization'
if findIDE in IDEs:
print ( "{}{}是{}." . format ( IDE, labels[ key] , IDEs[ findIDE] [ key] ) )
请输入IDE的名字:WEBSTORM
要查询IDE支持的编程语言(lang)还是所属组织机构(org)?lang
WEBSTORM支持的编程语言是['JavaScript'].
用format_map方法格式化字符串。
values1 = ( 1 , 2 , 'hello' )
str1 = "abc %d xyz, %d,%s world"
print ( str1 % values1)
abc 1 xyz, 2,hello world
values2 = { 'title' : '极客起源' , 'url' : 'https://geekori.com' , 'company' : '欧瑞科技' }
strl2 = """
<html>
<head>
<title>{title}</title>
<meta charset="utf-8" />
<head>
<body>
<h1>{title}</h1>
<a href="{url}">{company}</a>
</body>
</html>
"""
print ( str2. format_map( values2) )
<html>
<head>
<title>极客起源</title>
<meta charset="utf-8"/>
</head>
<body>
<h1>极客起源</h1>
<a href="https://geekori.com">欧瑞科技</a>
</body>
</html>
序列与迭代
获取字典中key的列表 获取字典中key-value对的列表 并行迭代 压缩序列 反转序列迭代
d = { "name" : "Bill" , "age" : 20 , "sex" : "男" , "salary" : 4567 }
for key in d:
print ( "{} = {}" . format ( key, d[ key] ) , end= " " )
name = Bill age = 20 sex = 男 salary = 4567
for key, value in d. items( ) :
print ( "{} = {}" . format ( key, value) , end = ' ' )
name = Bill age = 20 sex = 男 salary = 4567
list1 = [ 1 , 2 , 3 , 4 , 5 ]
list2 = [ 'a' , 'b' , 'c' , 'd' , 'e' ]
for i in range ( len ( list1) ) :
print ( "list1[{}] = {},list2[{}] = {}" . format ( i, list1[ i] , i, list2[ i] ) , end = " " )
print ( )
list1[0] = 1,list2[0] = a list1[1] = 2,list2[1] = b list1[2] = 3,list2[2] = c list1[3] = 4,list2[3] = d list1[4] = 5,list2[4] = e
for value in zip ( list1, list2) :
print ( value, end = " " )
print ( )
items = [ ]
for value in zip ( list2, list1) :
items. append( value)
d1 = dict ( items)
print ( d1)
print ( )
(1, 'a') (2, 'b') (3, 'c') (4, 'd') (5, 'e')
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
values1 = [ 4 , 1 , 5 , 6 , 3 , 1 , 7 , 9 ]
print ( sorted ( values1) )
[1, 1, 3, 4, 5, 6, 7, 9]
values2 = reversed ( values1)
for v in values2:
print ( v, end= " " )
print ( )
print ( '' . join( list ( reversed ( "abcdefg" ) ) ) )
9 7 1 3 6 5 1 4
gfedcba
names1 = { "Bill" : 20 , "Mike" : 30 , "John" : 50 }
names2 = names1
names1[ "Bill" ] = 45
print ( names2)
{'Bill': 45, 'Mike': 30, 'John': 50}
names1 = { }
print ( names2)
{'Bill': 45, 'Mike': 30, 'John': 50}
names1. clear( )
print ( names2)
{}
person1 = { "name" : "Mike" , "age" : 30 , "fullname" : [ "Bill" , "Gates" ] }
person2 = person1. copy( )
print ( 'person2' , person2)
person2 {'name': 'Mike', 'age': 30, 'fullname': ['Bill', 'Gates']}
person1[ "age" ] = 60
print ( 'person1' , person1)
print ( 'person2' , person2)
person1 {'name': 'Mike', 'age': 60, 'fullname': ['Bill', 'Gates']}
person2 {'name': 'Mike', 'age': 30, 'fullname': ['Bill', 'Gates']}
person1[ "fullname" ] [ 1 ] = "Colinton"
print ( 'person1' , person1)
print ( 'person2' , person2)
person1 {'name': 'Mike', 'age': 60, 'fullname': ['Bill', 'Colinton']}
person2 {'name': 'Mike', 'age': 30, 'fullname': ['Bill', 'Colinton']}
from copy import deepcopy
person1 = { "name" : "Mike" , "age" : 30 , "fullname" : [ "Bill" , "Gates" ] }
person2 = deepcopy( person1)
person1[ "fullname" ] [ 1 ] = "Conlinton"
print ( "person1" , person1)
print ( "person2" , person2)
person1 {'name': 'Mike', 'age': 30, 'fullname': ['Bill', 'Conlinton']}
person2 {'name': 'Mike', 'age': 30, 'fullname': ['Bill', 'Gates']}
newDict1 = { } . fromkeys( [ 'name' , 'company' , 'salary' ] )
print ( newDict1)
{'name': None, 'company': None, 'salary': None}
newDict2 = newDict1. fromkeys( ( 'name' , 'company' , 'age' ) )
print ( newDict2)
{'name': None, 'company': None, 'age': None}
newDict3 = newDict1. fromkeys( [ 'name' , 'company' , 'salary' ] , '没有值' )
print ( newDict3)
{'name': '没有值', 'company': '没有值', 'salary': '没有值'}
dict = { "name" : "Bill" , "age" : 30 }
print ( dict [ "age" ] )
30
print ( dict [ "company" ] )
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-61-3d8df2cf0f09> in <module>
----> 1 print(dict["company"])
KeyError: 'company'
print ( dict . get( 'salary' , None ) )
None
d = { 'help' : '帮助' , 'bike' : '自行车' , 'geek' : '极客' , 'China' : '中国' }
while True :
word = input ( '请输入英文单词:' )
if word == 'exit' :
break ;
value = d. get( word)
if value == None :
print ( "{}在字典中不存在." . format ( word) )
else :
print ( '"{}"的含义是"{}"' . format ( word, value) )
请输入英文单词:CHINA
CHINA在字典中不存在.
请输入英文单词:China
"China"的含义是"中国"
请输入英文单词:exit
d = { 'help' : '帮助' , 'bike' : '自行车' , 'plane' : '飞机' , 'China' : '中国' }
print ( d. items( ) )
dict_items([('help', '帮助'), ('bike', '自行车'), ('plane', '飞机'), ('China', '中国')])
for key_value in d. items( ) :
print ( "key" , "=" , key_value[ 0 ] , "value" , "=" , key_value[ 1 ] )
key = help value = 帮助
key = bike value = 自行车
key = plane value = 飞机
key = China value = 中国
for key, value in d. items( ) :
print ( "{} = {}" . format ( key, value) )
help = 帮助
bike = 自行车
plane = 飞机
China = 中国
print ( ( 'bike' , '自行车' ) in d. items( ) )
True
dict_items = d. items( )
d[ 'bike' ] = '自行车;摩托车;电动自行车'
print ( dict_items)
dict_items([('help', '帮助'), ('bike', '自行车;摩托车;电动自行车'), ('plane', '飞机'), ('China', '中国')])
print ( d. keys( ) )
dict_keys(['help', 'bike', 'plane', 'China'])
for key in d. keys( ) :
print ( key)
help
bike
plane
China
pop方法和popitem方法
pop方法用于获取指定的key的值,并从字典中弹出这个key-value对。 popitem方法用于返回字典中最后一个key-value对,并弹出key-value对。
dict = { 'a' : 40 , 'c' : 10 , 'b' : 12 , 'x' : 44 }
dict [ '1' ] = 3
dict [ '5' ] = 100
print ( dict . pop( 'b' ) )
for i in range ( len ( dict ) ) :
print ( dict . popitem( ) )
12
('5', 100)
('1', 3)
('x', 44)
('c', 10)
('a', 40)
print ( dict )
{}
setdefault方法
d = { "name" : "Bill" , "age" : 30 }
d[ 'salary' ] = 2000
d[ 'age' ] = 50
print ( d)
{'name': 'Bill', 'age': 50, 'salary': 2000}
print ( d. setdefault( "location" , "中国" ) )
print ( d)
print ( d. setdefault( "location" , "德国" ) )
print ( d)
中国
{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国'}
中国
{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国'}
print ( d)
{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国', 'date': '德国'}
del d[ 'date' ]
print ( d)
{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国'}
print ( d. setdefault( "date" ) )
print ( d)
None
{'name': 'Bill', 'age': 50, 'salary': 2000, 'location': '中国', 'date': None}
update方法
用一个字典中的key-value对更新另一个字典,该方法接收一个参数,该参数表示用作更新数据的字典数据源。
dict1 = {
'title' : '欧瑞科技' ,
'website' : 'https://geekori.com' ,
'description' : '从事在线IT课程研发和销售'
}
dict2 = {
'title' : '欧瑞科技' ,
'products' : [ '欧瑞科技' , '博客' , '读书频道' , '极客题库' , 'OriUnity' ] ,
'description' : '从事在线IT课程研发和销售,工具软件研发'
}
dict1. update( dict2)
print ( dict1)
{'title': '欧瑞科技', 'website': 'https://geekori.com', 'description': '从事在线IT课程研发和销售,工具软件研发', 'products': ['欧瑞科技', '博客', '读书频道', '极客题库', 'OriUnity']}
for item in dict1. items( ) :
print ( "key = {key} value = {value}" . format ( key = item[ 0 ] , value = item[ 1 ] ) )
key = title value = 欧瑞科技
key = website value = https://geekori.com
key = description value = 从事在线IT课程研发和销售,工具软件研发
key = products value = ['欧瑞科技', '博客', '读书频道', '极客题库', 'OriUnity']
values方法
values方法用于以迭代器形式返回字典中值得列表。与keys方法不同的是,values方法返回的值列表是可以有重复的,而keys方法返回的键值列表是不会有重复的key。
dict = {
'a' : 1 ,
'b' : 2 ,
'c' : 3 ,
'd' : 4 ,
'e' : 1
}
print ( dict . values( ) )
dict_values([1, 2, 3, 4, 1])
for value in dict . values( ) :
print ( value)
1
2
3
4
1
实战与练习
1.编写一个Python程序,在字典中添加1000个key-value对,其中key是随机产生的,随机范围是0~99。value任意指定。要求当key在字典中如果已经存在,仍然保留原来的key-value对。最后输出字典中所有的key-value对。
import random
dict = { }
for key in range ( 1000 ) :
dict . setdefault( random. randint( 0 , 100 ) , key* key)
print ( dict . items( ) )
dict_items([(94, 0), (40, 1), (7, 4), (29, 9), (73, 16), (99, 25), (76, 36), (48, 49), (37, 64), (65, 100), (0, 121), (35, 144), (10, 169), (63, 196), (3, 225), (2, 256), (95, 289), (5, 324), (28, 361), (84, 441), (27, 484), (100, 576), (4, 625), (92, 729), (44, 784), (64, 1024), (24, 1089), (88, 1156), (20, 1225), (22, 1296), (50, 1369), (77, 1600), (96, 1681), (66, 1764), (89, 1849), (87, 1936), (55, 2025), (81, 2116), (13, 2401), (23, 2500), (54, 2601), (30, 2809), (31, 3025), (33, 3136), (42, 3481), (53, 3600), (32, 3721), (82, 3969), (60, 4096), (80, 4489), (36, 4900), (68, 5184), (17, 5476), (78, 5776), (72, 5929), (41, 6241), (18, 6724), (62, 7056), (69, 7225), (90, 7396), (86, 7744), (1, 8281), (6, 8649), (43, 8836), (75, 9025), (97, 9216), (9, 10000), (74, 10404), (19, 11881), (79, 12996), (83, 13689), (93, 14161), (11, 14400), (71, 16384), (57, 17161), (47, 18225), (51, 20449), (16, 21025), (26, 21609), (45, 21904), (38, 22201), (98, 24964), (25, 25921), (52, 26896), (21, 28224), (8, 28561), (56, 31329), (70, 32761), (49, 34596), (61, 35344), (12, 36100), (15, 51076), (14, 51529), (59, 55225), (34, 66564), (67, 71289), (58, 80089), (39, 102400), (85, 145924), (46, 181476), (91, 240100)])
2.编写一个Python程序,从控制台输入一个包含整数的字符串,将字符串中的整数格式化为长度为10的格式,位数不足前面补0.例如,456格式化成0000000456。具体要求如下: – (1)不使用正则表达式。 – (2)使用字典格式化字符串。 – (3)将从控制台输入的字符串转换成字符串模板再进行格式化。 – (4)最后在控制台输出字符串模板和格式化结果。
s = input ( "请输入一个包含整数的字符串:" )
s1 = ''
number = ''
index = 0
d = { }
for i in range ( len ( s) ) :
c = s[ i]
if ord ( c) in range ( 48 , 57 ) :
number += c
else :
if len ( number) > 0 :
s1 += "{{number{}:010}}" . format ( index)
d[ 'number' + str ( index) ] = int ( number)
index += 1
number = ''
s1 += c
if len ( number) > 0 :
s1 += "{{number{}:010}}" . format ( index)
d[ 'number' + str ( index) ] = int ( number)
print ( s1)
print ( s1. format_map( d) )
请输入一个包含整数的字符串:ab43cd54xyz53
ab{number0:010}cd{number1:010}xyz{number2:010}
ab0000000043cd0000000054xyz0000000053