python 複数のdictionaryの使い方

 # dictionary

dict1 = dict()

dict1["apple"]="りんご"

dict1["orange"]="みかん"

dict1["orange"]="オレンジ"

dict1["lemon"]="レモン"

dict2 = dict()

dict2["apple"] = "green apple"

dict2["orange"] = "orange"

dict3 = dict()

dict3["apple"] = "ふじ"

print("dictionary dict1")

for eachkey, eachvalue in dict1.items():

    print (eachkey + "/" + eachvalue)

print("dictionary dict2")

for eachkey, eachvalue in dict2.items():

    print (eachkey + "/" + eachvalue)

print("dictionary dict3")

for eachkey, eachvalue in dict3.items():

    print (eachkey + "/" + eachvalue)

print("\ncommon keys in 3 dictionary")

common_keys = dict1.keys() & dict2.keys() & dict3.keys()

for eachkey in common_keys:

    print ('key = ' + eachkey)

    print ('val = dict1:' + dict1.get(eachkey))

    print ('val = dict2:' + dict2.get(eachkey))

    print ('val = dict3:' + dict3.get(eachkey))

print("\nall keys in 3 dictionary")

all_keys = dict1.keys() | dict2.keys() | dict3.keys()

for eachkey in all_keys:

    print ('key = ' + eachkey)

print("\nNot common keys in 3 dictionary")

not_common_keys = all_keys - common_keys

for eachkey in not_common_keys:

    print ('key = ' + eachkey)

    if eachkey in dict1:

        print ('val = dict1:' + dict1.get(eachkey))

    if eachkey in dict2:

        print ('val = dict2:' + dict2.get(eachkey))

    if eachkey in dict3:

        print ('val = dict3:' + dict3.get(eachkey))


以下、出力結果です。 

dictionary dict1

apple/りんご

orange/オレンジ

lemon/レモン

dictionary dict2

apple/green apple

orange/orange

dictionary dict3

apple/ふじ

common keys in 3 dictionary

key = apple

val = dict1:りんご

val = dict2:green apple

val = dict3:ふじ

all keys in 3 dictionary

key = orange

key = apple

key = lemon

Not common keys in 3 dictionary

key = orange

val = dict1:オレンジ

val = dict2:orange

key = lemon

val = dict1:レモン  

コメント

人気の投稿