四、数据类型_5.(3).dict - dict推导式

dict推导式

# 把dict中的key和value互换
vardict = {1:'a',2:2,'3':'c','d':4}

# 普通方法
newdict = {}
for k,v in vardict.items() :
    newdict[v] = k
print(newdict)

# dict推导式
newdict = {v:k for k,v in vardict.items()}
print(newdict)

# 注:set推导式
newdict = {v for k,v in vardict.items()}
print(newdict,type(newdict))

{'a': 1, 2: 2, 'c': '3', 4: 'd'}
{'a': 1, 2: 2, 'c': '3', 4: 'd'}
{2, 4, 'c', 'a'} <class 'set'>
# 把dict中,value为偶数的项保留并交换key和value
vardict = {'a':1,'b':2,'c':3,'d':4}

# 普通方法
newdict = {}
for k in vardict :
    if vardict[k] % 2 == 0 :
        newdict[vardict[k]] = k
print(newdict)

# dict推导式
newdict = {v:k for k,v in vardict.items() if v % 2 == 0}
print(newdict)

{2: 'b', 4: 'd'}
{2: 'b', 4: 'd'}
上一篇:学习数据结构二实现队列


下一篇:简单背包问题