Home > Blockchain >  How to separate dictionary values into new dictionaries?
How to separate dictionary values into new dictionaries?

Time:09-08

I have two dictionaries :

d_1 = {'A':0, 'B':0, 'C':0}
d_2 = {'A':60, 'B':30, 'C':10}

I've used such expression :

d3 = {k: (d1[k],d2[k]) for k in d1.keys()}

And as outcome received :

{'A': (0, 60), 'B': (0, 30), 'C': (0, 10)} 

The question is how to perform reverse expression to separate list from this outcome back to:

d_1 = {'A':0, 'B':0, 'C':0}
d_2 = {'A':60, 'B':30, 'C':10}

CodePudding user response:

Create two empty dictionaries (d1 & d2) then iterate over the d3 items as follows:

d3 = {'A': (0, 60), 'B': (0, 30), 'C': (0, 10)}

d1 = {}
d2 = {}

for k, v in d3.items():
    d1[k], d2[k] = v

print(d1)
print(d2)

Output:

{'A': 0, 'B': 0, 'C': 0}
{'A': 60, 'B': 30, 'C': 10}

CodePudding user response:

Iterate through the dictionary while adding key/value to d1 and d2:

d_1 = {}
d_2 = {}
data = {'A': (0, 60), 'B': (0, 30), 'C': (0, 10)}

for k, v in data.items():
    v1, v2 = v
    d_1[k] = v1
    d_2[k] = v2

print(d_1, d_2)

Output:

{'A': 0, 'B': 0, 'C': 0}
{'A': 60, 'B': 30, 'C': 10}

CodePudding user response:

Try:

d3 = {"A": (0, 60), "B": (0, 30), "C": (0, 10)}

d_1, d_2 = map(dict, zip(*(((k, a), (k, b)) for k, (a, b) in d3.items())))

print(a)
print(b)

Prints:

{'A': 0, 'B': 0, 'C': 0}
{'A': 60, 'B': 30, 'C': 10}

CodePudding user response:

Like this?

data = {'A': (0, 60), 'B': (0, 30), 'C': (0, 10)}

d_1, d_2 = {}, {}

for key, value in data.items():
    d_1[key] = value[0]
    d_2[key] = value[1]

print(d_1)
{'A': 0, 'B': 0, 'C': 0}

print(d_2)
{'A': 60, 'B': 30, 'C': 10}

or more generally using a list of dicts:

data = {'A': (0, 60), 'B': (0, 30), 'C': (0, 10)}

result = []
for key, value in data.items():
    for i, v in enumerate(value):
        try:
            result[i][key] = v
        except IndexError:
            result.append({key: v})

print(result)
[{'A': 0, 'B': 0, 'C': 0}, {'A': 60, 'B': 30, 'C': 10}]

CodePudding user response:

Using dict comprehension with value unpacking:

d3 = {'A': (0, 60), 'B': (0, 30), 'C': (0, 10)}
d_1 = {k: v for k,(v, _) in d3.items()}
d_2 = {k: v for k,(_, v) in d3.items()}

print(d_1)
print(d_2)

# {'A': 0, 'B': 0, 'C': 0}
# {'A': 60, 'B': 30, 'C': 10}
  • Related