我的python字典循环代码有什么问题?

时间:2016-05-02 18:51:32

标签: python loops dictionary

我有一份货币清单:

{'USD':1.316,'GBP':0.812,'LTL':3.4528}

我需要输出:

{'LTL':{'GBP':0.812,'USD':1.316},

'GBP':{'LTL':3.4528,'USD':1.316},

'美元':{'LTL':3.4528,'GBP':0.812},

'EUR':{'LTL':3.4528,'GBP':0.812,'USD':1.316}}

我的代码在这里:

from copy import deepcopy
def currency(dictionary):

    new_dictionary = {}
    for key, value in dictionary.items():
        new_dictionary[key] = dictionary
        new_dictionary['EUR'] = dictionary
    print(new_dictionary)

    for k, v in new_dictionary.items():
        copy = deepcopy(v)
        for i, j in copy.items():
            if k in i:
                del v[i]
    return new_dictionary

print(currency({'USD': 1.316, 'GBP': 0.812, 'LTL': 3.4528}))

但我得到空值,当我尝试这样的时候,它有效:

from copy import deepcopy

def currency(dictionary):
    for key, value in dictionary.items():
        copy = deepcopy(value)
        for i, j in copy.items():
            if key in i:
                del value[i]

    return dictionary

print(currency({'GBP': {'GBP': 0.812, 'USD': 1.316, 'LTL': 3.4528},     'USD': {'GBP': 0.812, 'USD': 1.316, 'LTL': 3.4528},'LTL': {'GBP': 0.812, 'USD': 1.316, 'LTL': 3.4528},'EUR': {'GBP': 0.812, 'USD': 1.316, 'LTL': 3.4528}}))

我不明白区别在哪里。

1 个答案:

答案 0 :(得分:0)

试试这个:

In [8]: res = {}

In [14]: for k, v in ccy.items():
   ....:     tdict=deepcopy(ccy)
   ....:     tdict.pop(k)
   ....:     res[k]=tdict
   ....:

In [15]: res
Out[15]:
{'GBP': {'LTL': 3.4528, 'USD': 1.316},
 'LTL': {'GBP': 0.812, 'USD': 1.316},
 'USD': {'GBP': 0.812, 'LTL': 3.4528}}