新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
創(chuàng)新互聯(lián)Python教程:python判斷兩個(gè)字典是否相同
python自帶的數(shù)據(jù)結(jié)構(gòu)dict非常好用,之前不知道怎么比較2個(gè)字典是否相同,做法是一個(gè)一個(gè)key比較過(guò)去。。。

現(xiàn)在想到可以直接用==進(jìn)行判斷?。?!
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
print(a == b == c == d == e)Python內(nèi)部對(duì)==進(jìn)行了重載,幫你實(shí)現(xiàn)了對(duì)key和value進(jìn)行判斷。
怎樣在兩個(gè)字典中尋找相同點(diǎn)(比如相同的鍵、相同的值等)?
解決方案
考慮下面兩個(gè)字典:
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}尋找兩個(gè)字典的相同點(diǎn),可以在兩字典的 keys()或者 items() 方法返回結(jié)果上執(zhí)行集合操作。例如:
# Find keys in common
a.keys() & b.keys() # Return { 'x', 'y' }
# Find keys in a that are not in b
a.keys() - b.keys() # Return { 'z' }
# Find (key,value) pairs in common
a.items() & b.items() # Return { ('y', 2) } 網(wǎng)頁(yè)標(biāo)題:創(chuàng)新互聯(lián)Python教程:python判斷兩個(gè)字典是否相同
文章位置:http://www.5511xx.com/article/cdopjdp.html


咨詢(xún)
建站咨詢(xún)
