2024年10月27日 星期日

[Python] 字典 dict { } 的 key, value 鍵、值 互換

.[Python] 字典 dict { } 的 key, item 鍵、值 互換
 
--- --- --- --- --- --- --- --- ---
(1) 字典鍵值互換, 方法一 for 循環:
mydict = {'a': 1, 'b': 2, 'c': 3}
mydict_new = {}
for key, value in mydict.items():
    mydict_new[value] = key

print(mydict)
print(mydict_new)

---
>>> mydict = {'a': 1, 'b': 2, 'c': 3}
>>> mydict_new = {}
>>> for key, value in mydict.items():
...      mydict_new[value] = key
...
>>> print(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> print(mydict_new)
{1: 'a', 2: 'b', 3: 'c'}
>>>

--- --- --- --- --- --- --- --- ---
(2) 字典鍵值互換, 方法二 列表生成器 generator:
mydict = {'a': 1, 'b': 2, 'c': 3}
mydict_new = dict([value, key] for key, value in mydict.items())
print(mydict)
print(mydict_new)

---
>>> mydict = {'a': 1, 'b': 2, 'c': 3}
>>> mydict_new = dict([value, key] for key, value in mydict.items())
>>> print(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> print(mydict_new)
{1: 'a', 2: 'b', 3: 'c'}

--- --- --- --- --- --- --- --- ---
(3) 字典鍵值互換, 方法三 zip:
mydict = {'a': 1, 'b': 2, 'c': 3}
mydict_new = dict(zip(mydict.values(), mydict.keys()))
print(mydict)
print(mydict_new)

---
>>> mydict = {'a': 1, 'b': 2, 'c': 3}
>>> mydict_new = dict(zip(mydict.values(), mydict.keys()))
>>> print(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> print(mydict_new)
{1: 'a', 2: 'b', 3: 'c'}





沒有留言:

張貼留言