user4544020
user4544020

Reputation:

How to alter the keys in a dictionary in python

This is my code:

def vmm(v, M):
    d = {}
    domain = [(i,j) for i in M.D[0] for j in M.D[1]]
    for k in M.D[1]:
        for i in domain:
            if i[1] == k:
                f = 0
                f += M[i]*v[i[0]]
                d[i] = f
    return d

it returns:

{(3, 'b'): 0, (3, 'a'): 0, (1, 'b'): 2, (2, 'a'): -8, (3, 'c'): 0, (2, 'b'): 0, (2, 'c'): 0, (1, 'a'): 0, (1, 'c'): 0}

Which is almost what i want, i would like instead each key to be the second element of the tuple, so they keys will be 'a','b' or 'c', where the values are the sum of all the values with 'a', 'b','c' as a second element.

I have tried replacing the last line before the return statement with:

d[1][i] = f

This returns a dictionary with all values equal to zero, this is not what i want.

EDIT

def vector_matrix_mul(v, M):
    d = {}
    e = {}
    domain = [(i,j) for i in M.D[0] for j in M.D[1]]
    for k in M.D[1]:
        for i in domain:
            if i[1] == k:
                f = 0
                f += M[i]*v[i[0]]
                d[i] = f
    for i in d: 
        for m in M.D[1]: #{'a', 'b', 'c'}
            if i[1] == m:
                for k in M.D[0]:
                    F = 0
                    F += i[m,k]
                    e[m] = F
    return e  

Still no luck, if someone could help me with this, i don't want to use extra modules, just want to fix my code please.

M = Mat(M.D,M.f)
v = Vec(v.D,v.f)

so M.D is the 'domain' of the matrix and M.f is the function of the matrix. similarly with the vector.

an example...

>>> v1 = Vec({1, 2, 3}, {1: 1, 2: 8})
>>> M1 = Mat(({1, 2, 3}, {'a', 'b', 'c'}), {(1, 'b'): 2, (2, 'a'):-1, (3, 'a'): 1, (3, 'c'): 7})

Note the different dimensions in the domain of v and M.

Upvotes: 1

Views: 73

Answers (2)

tanmoy
tanmoy

Reputation: 170

I dont know if I have understood your question. Let me try.
To alter a key in dictionary:

  • find if the key k_old exists
  • copy its value to a variable v
  • remove the entry corresponding to k_old from the dictionary
  • add a new entry with new key k_new with value v

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

use a defaultdict using the key from the tuple and summing each value:

from collections import defaultdict
d=defaultdict(int)

domain = zip(M.D[0], M.D[1])
for vl, k in domain:
    d[k] +=  M[(vl,k)] * v[vl]

I don't understand where for k in M.D[1] comes into it as you already have all the M.D[1] items in your domain list.

Upvotes: 1

Related Questions