eatonphil
eatonphil

Reputation: 13712

dictionary not storing multiple values for same key

Here is my code:

import math

def distance(argv):
    comp_diff = []
    for comp_1, comp_2 in argv.iteritems():
        comp_diff.append(comp_1-comp_2)
        print comp_2
    return math.sqrt(sum([math.pow(comp,2) for comp in comp_diff]))

if __name__ == '__main__':
    components = {0:4, 0:5, 0:4}
    d = distance(components)
    print d

The output is:

4
4.0

Whereas it should be:

4
5
4
5.1

Why is this happening? I changed the length of the components dictionary and it it became apparent that only the last key value pair shows up and is iterated through. Why is this? Pardon my novice in Python.

Upvotes: 0

Views: 186

Answers (2)

dnozay
dnozay

Reputation: 24344

You are not using the dictionary correctly:

>>> components = {0:4, 0:5, 0:4}
>>> components
{0: 4}

you could use a list of tuples instead.

import math

def distance(argv):
    comp_diff = []
    for comp_1, comp_2 in argv:
        comp_diff.append(comp_1-comp_2)
        print comp_2
    return math.sqrt(sum([math.pow(comp,2) for comp in comp_diff]))

if __name__ == '__main__':
    components = [(0,4), (0,5), (0,4)]
    d = distance(components)
    print d

Upvotes: 3

user2357112
user2357112

Reputation: 281923

A dict can only have one value per key. Python is throwing away 2 of those key-value pairs.

(Unrelated note that might help you avoid future trouble: Dict key-value pairs are unordered. Don't try to rely on any particular iteration order.)

Upvotes: 2

Related Questions