Python 字典操作 总结

字典

team={}#创建字典
team['aaa']=1#往字典里添加元素
team['bbb']=2

team.keys()
dict_keys(['aaa', 'bbb'])

'aaa' in team.keys()
True
'la' in team.keys()
False

team.values()
dict_values([1, 2])
3 in team.values()
False
2 in team.values()
True

>>>team.pop('aaa')#删除指定key的键值对,返回对应的值,这是在命令行里的写法,不在命令行里想获取pop弹出的值可见片段2
1
>>>team
{'bbb': 2}
>>>team['ccc']=3
>>>team
{'bbb': 2, 'ccc': 3}
>>>team.clear()#把所有键值对都删除
>>>team
{}
#片段2:
team={}
team['aaa']=1
team['bbb']=2
temp=team.pop('aaa')

>>>team
{'bbb': 2}
>>>temp
1

team={}
team['aaa']=1
team['bbb']=2
print(team)
team['bbb']='ccc'#直接这样改就好了
print("After modify",team)

输出:
{'aaa': 1, 'bbb': 2}
After modify {'aaa': 1, 'bbb': 'ccc'}

按key查

team={}
team['aaa']=1
team['bbb']=2
#按key查 .get()的用法
avalue=team.get('aaa')#按照key查找
print("avalue is",avalue)
print("type of avalue is",type(avalue))

cvalue=team.get('c')#如果没有这个key,返回的是None
print("cvalue is",cvalue)
print("type of cvalue is",type(cvalue))
print(cvalue is None)
#结果如下:
avalue is 1
type of avalue is <class 'int'>
cvalue is None
type of cvalue is <class 'NoneType'>
True

#setdefault的用法:按key查找并返回对应的value,如果key存在,返回对应值;如果key不存在,创建对应的key-value(value是None) 这也是和.get()方法不同的地方
print(team.setdefault('aaa'))#直接这样写
print(team)
print(team.setdefault('eee'))
print(team)
#结果如下:
1
{'aaa': 1, 'bbb': 2}
None
{'aaa': 1, 'bbb': 2, 'eee': None}

#按key查,python2里.has_key()的用法
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  dict.has_key('Age')
print "Value : %s" %  dict.has_key('Sex')
#输出为
Value : True
Value : False

#按key查,python3里.__contains__()
dict3 = {'name':'z','Age':7,'class':'First'};
print("Value : ",dict3.__contains__('name'))
print("Value : ",dict3.__contains__('sex'))
#输出结果
Value :  True
Value :  False

#按key查,.keys()是不能被下标索引的
>>>team.keys()
dict_keys(['aaa', 'bbb', 'ccc'])
type(team.keys())
<class 'dict_keys'>
team.keys()[0]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'dict_keys' object does not support indexing

team.keys()
dict_keys(['aaa', 'bbb', 'ccc'])
'aaa' in team.keys()
True
'aaa ' in team.keys()
False
'b' in team.keys()
False

按value查

team.values()
dict_values([1, 2, 3])
1 in team.values()
True
'1' in team.values()
False

遍历 .items() 旧貌新颜

在Python2.x中,items( )用于 返回一个字典的拷贝列表【Returns a copy of the list of all items (key/value pairs) in D】,占额外的内存。
iteritems() 用于返回本身字典列表操作后的迭代【Returns an iterator on all items(key/value pairs) in D】,不占用额外的内存。

# -*- coding: UTF-8 -*-
#Python2
a={'aaa':1,'bbb':2}
print a.keys() #['aaa', 'bbb']
print a.items()#[('aaa', 1), ('bbb', 2)]
print type(a.items())#<type 'list'>
print a.iteritems()#<dictionary-itemiterator object at 0x7f325524d940>
print type(a.iteritems())#<type 'dictionary-itemiterator'>
print '-------------------------------'
for k,v in a.iteritems():
    print k,v
-------------------------------
#aaa 1
#bbb 2
for k,v in a.items(): #Python2和Python3公用的遍历用万能写法
    print k,v
#aaa 1
#bbb 2
#!/usr/bin/python
#Python3
a={'aaa':1,'bbb':2}
print (a.keys())#dict_keys(['aaa', 'bbb'])
print(type(a.keys()))#<class 'dict_keys'>
print (a.items())#dict_items([('aaa', 1), ('bbb', 2)])
print (type(a.items()))#<class 'dict_items'>
print (a.iteritems())#语法错误,python3就没有iteritems()
print (type(a.iteritems()))
print ('-------------------------------')
for k,v in a.iteritems():#Python2和Python3公用的遍历用万能写法
    print (k,v)
#aaa 1
#bbb 2

Python 3.x 里面,iteritems() 和 viewitems() 这两个方法都已经废除了,而 items() 得到的结果是和 2.x 里面 viewitems() 一致的。在3.x 里 用 items()替换iteritems() ,可以用于 for 来循环遍历。

team={}
team['aaa']=1
team['bbb']=2
team['ccc']=3

print("team.items type is ",type(team.items()))
for i in team.items():
    print(i)
    print(type(i))
print("----------------------------------")
for i in team.items():
    print ("key is ",i[0],"value is",i[1])
print("----------------------------------")
for i,j in team.items():
    print ("key is ",i,"value is",j)

#结果:
team.items type is  <class 'dict_items'>
('aaa', 1)
<class 'tuple'>
('bbb', 2)
<class 'tuple'>
('ccc', 3)
<class 'tuple'>
----------------------------------
key is  aaa value is 1
key is  bbb value is 2
key is  ccc value is 3
----------------------------------
key is  aaa value is 1
key is  bbb value is 2
key is  ccc value is 3

for key in team.__iter__():
     print (key)
#结果
aaa
bbb
ccc

>>>type(team.__iter__())
<class 'dict_keyiterator'>

python3里好像没有iteritems(),iterkeys(),itervalues()了


#只遍历key或者只遍历value
>>>type(team.keys())
<class 'dict_keys'>
>>>team.keys()
dict_keys(['aaa', 'bbb', 'ccc'])
>>>type(team.values())
<class 'dict_values'>
>>>team.values()
dict_values([1, 2, 3])

for i in team.values():
    print (i)

1
2
3

以另一个字典来更新当前字典:永结同心

team={}
team['aaa']=1
team['bbb']=2
team['ccc']=3

mate={}
mate['ccc']=4
mate['ddd']=5
team.update(mate)
#结果
>>>team
{'aaa': 1, 'bbb': 2, 'ccc': 4, 'ddd': 5}

排序

万能写法 python2 python3通用 对整个字典按key或value排序

#python2 python3通用,结果一样
team={}
team['bb']=3
team['cc']=1
team['aa']=2

def sortedDictValues1(adict):
     a=sorted(adict.items(), key=lambda d: d[0])#d[1]是根据value排序,d[0]是根据key排序
     #     a=sorted(adict.items(), key=lambda d: d[0],reverse=True) 反序带reverse
     return a
print(team)
temp=sortedDictValues1(team)
print(temp)
print(team)
#结果
{'bb': 3, 'cc': 1, 'aa': 2}
[('aa', 2), ('bb', 3), ('cc', 1)]
{'bb': 3, 'cc': 1, 'aa': 2}

对key排序 sorted(),不修改原字典

#python3
#!/usr/bin/python
team={}
team['bb']=3
team['cc']=1
team['aa']=2
print(team)
print(sorted(team.keys()))
print(team)
print(sorted(team.values()))
print(team)

{'bb': 3, 'cc': 1, 'aa': 2}
['aa', 'bb', 'cc']
{'bb': 3, 'cc': 1, 'aa': 2}
[1, 2, 3]
{'bb': 3, 'cc': 1, 'aa': 2}

例题 微软2019实习生笔试第四题

题目意思是
一共有numOfKids那么多小朋友,每个小朋友有一个编号,从0开始编,每个小朋友还有一个力量值
有个箱子里面有cardDrawn那么多张卡片
每张卡片上有两个数,代表两个小朋友的编号,一张卡片上的两个小朋友就分到一队
如果没有被卡片抽到的小朋友,就自成一队
求所有队伍里力量值最大的一队

numOfKids=6
cardDrawn=3
teamPair=[[1,2],[2,3],[4,5]]
strength=[11,2,3,15,8,22]
def func(numOfKids,cardDrawn,teamPair,strength):
    teaminfo = {}  # {1: 0, 2: 0, 3: 0, 4: 1, 5: 1} #记录每个人 与 其所在队伍号
    team_strength_map = {}  # 记录了每个队伍的队伍号,与该队伍成员的strength和 的对应关系
    teamNo=0#初始化队伍号,从0开始
    for onePair in teamPair:
        print(onePair)
        FirstPerson=teaminfo.setdefault(onePair[0])
        SecondPerson=teaminfo.setdefault(onePair[1])
        if FirstPerson is None and SecondPerson is None:#如果两个人都没被分组,那么为该二人新建一个队伍号
            print("Double None")
            teaminfo[onePair[0]]=teamNo
            teaminfo[onePair[1]]=teamNo
            team_strength_map[teamNo]=strength[onePair[0]]+strength[onePair[1]]
            teamNo=teamNo+1
        if FirstPerson is None and SecondPerson is not None:#如果第一个人还没分组
            print("First None")
            teaminfo[onePair[0]]=teaminfo[onePair[1]]#把第二个人的组赋给第一个人的组
            team_strength_map[teaminfo[onePair[1]]] +=  strength[onePair[0]]#第二个人所在组的strength就加上第一个人贡献的strength
        if SecondPerson is None and FirstPerson is not None:#如果第二个人还没分组
            print("Second None")
            teaminfo[onePair[1]]=teaminfo[onePair[0]]#把第一个人的组赋给第二个人的组
            team_strength_map[teaminfo[onePair[0]]] += strength[onePair[1]]#第一个人所在组的strength就加上第二个人贡献的strength
    #print(teaminfo)
    #print(team_strength_map)
    tempMax=max(team_strength_map.values())
    for i in range(0,numOfKids):#遍历所有小朋友,寻找可怜的没有被分到组的小朋友非常有力量,可能是实际上的最大值
        if i not in teaminfo.keys():
             if strength[i]>tempMax:
                 tempMax=strength[i]
    print("FinalStrengthMax is",tempMax)
    return  tempMax
result=func(numOfKids,cardDrawn,teamPair,strength)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python中的字典(Dictionary)是一种可变容器,可以存储键值对(key-value pairs)。以下是Python字典的基本操作: 1. 创建字典:使用花括号{}或者dict()函数创建字典 ``` dict1 = {'name': 'Alice', 'age': 25, 'city': 'Shanghai'} dict2 = dict([('name', 'Bob'), ('age', 30), ('city', 'Beijing')]) ``` 2. 访问字典元素:使用键访问字典中对应的值 ``` print(dict1['name']) # 输出:'Alice' ``` 3. 修改字典元素:使用键来修改字典中对应的值 ``` dict1['age'] = 26 ``` 4. 添加字典元素:使用新的键值对来添加元素 ``` dict1['gender'] = 'female' ``` 5. 删除字典元素:使用del关键字删除指定的键值对 ``` del dict1['city'] ``` 6. 遍历字典:使用for循环遍历字典中的键值对 ``` for key, value in dict1.items(): print(key, value) ``` 7. 获取字典的键和值:使用keys()和values()方法分别获取字典中的键和值 ``` keys = dict1.keys() values = dict1.values() ``` 8. 判断键是否在字典中:使用in关键字判断指定的键是否在字典中 ``` if 'name' in dict1: print('name exists in dict1') ``` 以上就是Python字典的基本操作。 ### 回答2: Python字典是一种可变的数据类型,它是以键值对的形式存储数据的。 1. 创建字典: 可以使用大括号{}或者dict()函数来创建字典。例如: ```python my_dict = {} # 创建一个空字典 my_dict = dict() # 创建一个空字典 my_dict = {"name": "Tom", "age": 20} # 创建一个包含键值对的字典 ``` 2. 访问字典中的元素: 可以通过使用键来访问字典中的值。例如: ```python name = my_dict["name"] # 获取键为"name"的值 age = my_dict.get("age") # 使用get()函数获取键为"age"的值 ``` 3. 更新字典元素: 可以通过赋值的方式来更新字典中的键值对。例如: ```python my_dict["name"] = "Jerry" # 更新键为"name"的值为"Jerry" my_dict.update({"age": 25}) # 使用update()函数来更新键为"age"的值为25 ``` 4. 删除字典元素: 可以使用del关键字或者pop()函数来删除字典中的键值对。例如: ```python del my_dict["name"] # 删除键为"name"的键值对 my_dict.pop("age") # 使用pop()函数删除键为"age"的键值对 ``` 5. 遍历字典: 可以使用for循环来遍历字典。例如: ```python for key in my_dict: print(key, my_dict[key]) # 打印键和对应的值 ``` 6. 判断字典中是否存在某个键: 可以使用in关键字来判断字典中是否存在某个键。例如: ```python if "name" in my_dict: print("Key 'name' exists in the dictionary!") ``` 总结Python字典是一种非常有用的数据结构,它提供了快速查找和存储数据的功能。通过基本操作,我们可以轻松地创建、访问、更新和删除字典中的键值对。 ### 回答3: Python字典是一种无序的数据结构,用于存储键-值对。它可以通过键来唯一地标识和访问值。 字典的基本操作包括: 1. 创建字典:可以使用大括号 {} 或者 dict() 函数来创建一个空字典;也可以在大括号中填写键-值对来创建一个非空字典。 2. 添加键-值对:可以使用赋值运算符(=)为字典指定键-值对,如 dict[key] = value。 3. 访问值:可以通过键来访问字典中对应的值,如 dict[key]。 4. 修改值:通过指定字典的键来修改对应的值,如 dict[key] = new_value。 5. 删除键-值对:可以使用 del 关键字来删除字典中的指定键-值对,如 del dict[key]。 6. 遍历字典:可以使用 for 循环来遍历字典的键或者键-值对,如 for key in dict 和 for key, value in dict.items()。 7. 获取字典长度:使用 len() 函数可以获取字典中键-值对的个数。 8. 检查键是否存在:可以使用 in 和 not in 运算符来检查某个键是否存在于字典中。 9. 获取所有键或者所有值:可以使用 dict.keys() 获取字典中的所有键,使用 dict.values() 获取字典中的所有值。 10. 清空字典:使用 clear() 方法可以清空字典中的所有键-值对。 总之,字典是一种灵活且常用的数据结构,可以用来存储和操作键-值对,具有方便的访问和修改功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值