在字典中转换2元组键并将其作为字典值添加到新字典中

时间:2018-04-12 04:16:30

标签: python dictionary tuples

所以我有价值观:

values = {(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 0}

我希望将上面的字典转换为:

values = {0: {0: 0, 1: 1}, 1: {0: 1, 1: 0}}

我的职能:

def convert(values : {(int,int): int}) -> {int: {int: int}}:
    dictionary = {}
    l = []

    for k in d.keys():
        l.append(k)

    for k,v in d.items():
        for i in l:
            if i == k:
                dictionary[v] = dict(l)

    return dictionary

但我将此作为输出:

values = {0: {0: 1, 1: 1}, 1: {0: 1, 1: 1}}

4 个答案:

答案 0 :(得分:11)

循环和dict.setdefault()可以这样做:

代码:

values = {(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 0}

result = {}
for k, v in values.items():
    result.setdefault(k[0], {})[k[1]] = v

print(result)

结果:

{0: {0: 0, 1: 1}, 1: {0: 1, 1: 0}}

答案 1 :(得分:10)

你只想分组。惯用的方法是使用defaultdict

>>> from collections import defaultdict
>>> values = {(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 0}
>>> new_values = defaultdict(dict)
>>> for (x,y), v in values.items():
...     new_values[x][y] = v
...
>>> new_values
defaultdict(<class 'dict'>, {0: {0: 0, 1: 1}, 1: {0: 1, 1: 0}})
>>> 

答案 2 :(得分:2)

我建议你采用更通用的方法:

from collections import defaultdict

def tree():
    def the_tree():
        return defaultdict(the_tree)
    return the_tree()

t = tree()
for (x, y), z in values.items():
    t[x][y] = z

To&#34; close&#34;来自进一步添加的树的任何节点,只需将其默认工厂设置为None。例如,将它密封在行李箱上:

>>> t.default_factory = None
>>> t[2]
# KeyError

答案 3 :(得分:1)

任意深度的解决方案:

def convert_tupledict(d):
    result = {}
    for ks, v in d.items():
        subresult = result
        *kis, ks = ks
        for ki in kis:
            if ki in subresult:
                subresult = subresult[ki]
            else:
                subresult[ki] = subresult = {}
        subresult[ks] = v
    return result

然后我们可以用:

来调用它
convert_tupledict({(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 0})

对于2元组,以下说法应该足够了:

def convert_2tupledict(d):
    result = {}
    for (k1, k2), v in d.items():
        result.setdefault(k1, {})[k2] = v
    return result