交换字典的内容

时间:2013-12-08 16:03:13

标签: python dictionary

我有一个字典,其中要交换键和值。例如:

dic = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi",
  "phoenix":"arizona"}

输出应为:

{"indiana":"indianapolis", "ohio":"columbus", "mississippi":"jackson",
  "arizona":"phoenix"}

以下是我尝试但限制条件是只应使用sorted()split()函数,不应使用其他内置函数(如keys(),{{1 },values()items())。不确定如何进一步。有人可以帮忙吗?我是词典的新手。

lambda

4 个答案:

答案 0 :(得分:3)

  

仅应使用.sorted().split()个函数

使用sorted和词典理解:

>>> dic = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi", "phoenix":"arizona"}
>>> {dic[k]:k for k in sorted(dic)}
{'ohio': 'columbus', 'mississippi': 'jackson', 'arizona': 'phoenix', 'indiana': 'indianapolis'}

sorted按排序顺序返回字典的键,但最终字典的顺序将是任意的。上面的代码相当于:

>>> sorted(dic)
['columbus', 'indianapolis', 'jackson', 'phoenix']
>>> new_dic = {}
>>> for k in sorted(dic):
...     new_dic[dic[k]] = k
...     
>>> new_dic
{'ohio': 'columbus', 'mississippi': 'jackson', 'arizona': 'phoenix', 'indiana': 'indianapolis'}

<强>更新

def interchange(input_dict):
    return {input_dict[k]:k for k in sorted(input_dict)}
... 
>>> interchange(dic)
{'ohio': 'columbus', 'mississippi': 'jackson', 'arizona': 'phoenix', 'indiana': 'indianapolis'}

答案 1 :(得分:1)

使用dict理解:

>>> dic = {"indianapolis":"indiana", "columbus":"ohio",
...        "jackson":"mississippi", "phoenix":"arizona"}
>>> {dic[key]: key for key in dic}
{'ohio': 'columbus', 'mississippi': 'jackson',
 'arizona': 'phoenix', 'indiana': 'indianapolis'}

答案 2 :(得分:0)

一些不错的选择:

dic = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi",
  "phoenix":"arizona"}

newDict = dict(zip(dic.values(),dic.keys()))

print newDict

<强>输出:

{'ohio': 'columbus', 'mississippi': 'jackson', 'arizona': 'phoenix', 'indiana': 'indianapolis'}

<强>解释

zip()返回一个元组列表(dictionery),zip的参数按顺序颠倒......

没有python方法:

dic = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi",
  "phoenix":"arizona"}

newDict = {}

for key, item in dic.iteritems():
    newDict.update({item: key})

print newDict

<强>输出:

{'ohio': 'columbus', 'mississippi': 'jackson', 'arizona': 'phoenix', 'indiana': 'indianapolis'}

答案 3 :(得分:0)

非常简单

tuple_list = zip(dic.values(),dic.keys())
Result = dict(tuple_list)

将产生所需的输出

{'arizona': 'phoenix',
 'indiana': 'indianapolis',
 'mississippi': 'jackson',
 'ohio': 'columbus'}

修改 一线解决方案

{ dic[Key]:Key for Key in list(dic) }