Thomas
Thomas

Reputation: 11

Python: convert x,y,z data to dictionary with x,y as tuple keys

I know little about Python and my Google skills are failing me. I have imported a csv and gotten a list where I have:

a = ([x1,y1,z1]...[xn,yn,zn])

and I want a dictionary where unique x,y combinations have all of their z values. I created a list of the unique x,y values as tuples, but I'm not sure how to turn them into a dictionary where the tuples are the keys and the z values are listed for each key. Anyone have any pointers?

The specific use in this scenario is I have a variety of x,y coordinates that have a value associated with them, and the end goal is to find the highest value for each of the x,y coordinates, and it seemed like creating a dictionary was the correct way.

Example: Given

a = ([1, 1, 10], [1, 1, 20], [1, 1, 30], [1, 2, 10], [1, 2, 20]) b = dict()

I want to produce a dictionary where print(b) returns

{(1,1): 10, 20, 30, (1,2): 10, 20}

Edit again:

I tried the methods below and they seemed to work, but then I realized my the values of my .csv were imported as strings. I started searching around for a solution, and saw a suggestion to use pandas. Well, 30 minutes later and now I have written something that imports, sorts by the x,y columns, and exports the max values from each in about 10 lines, so I was approaching this in a very clunky way to begin with. Thanks for the pointers though :)

Upvotes: 0

Views: 1322

Answers (5)

snamef
snamef

Reputation: 195

Use setdefault

d = {}
for [x, y, z] in a:
 d.setdefault((x,y),[]).append(z)

Upvotes: 0

peer
peer

Reputation: 4699

For what its worth, this is a simple way of getting the result you specified:

a = ([1, 1, 10], [1, 1, 20], [1, 1, 30], [1, 2, 10], [1, 2, 20])                                                                                                                  

b = {} 
for [x,y,z] in a: 
    if (x,y) in b: 
        b[(x,y)].append(z) 
    else: 
        b[(x,y)] = [z] 


b == {(1, 1): [10, 20, 30], (1, 2): [10, 20]}

You can then get the max values by

b_max = {k:max(v) for k,v in b.items()}

Or, you collect max values right away:

b = {} 
 for [x,y,z] in a: 
    if (x,y) in b: 
        if b[(x,y)] < z: 
            b[(x,y)] = z 
    else: 
        b[(x,y)] = z 

Upvotes: 0

Superior
Superior

Reputation: 885

if you are interested in only the highest value do

b = dict()

for entry in a:
    x, y, z = *entry # tuple unpacking
    if b.get((x,y), float('-inf')) < z:
        b[x,y] = z

print(b)

if you want to have all of the values (warning: could be space-consuming, and than time-consuming if you will again traverse all of the z values and compare them)

b = dict()

for entry in a:
    x, y, z = *entry # tuple unpacking
    b.get((x,y), []).append(z)

print(b)

Upvotes: 0

Telmo Trooper
Telmo Trooper

Reputation: 5684

Alternative 1: Key as single value composed of others

If your keys can be parsed as text, you can use a single value composed of them as key:

a = [['a','b','c'],['d', 'e', 'g']]

b = dict()

for entry in a:
  b[f"{entry[0]},{entry[1]}"] = entry[2]

print(b)

The resulting dictionary in this case is {'a,b': 'c', 'd,e': 'g'}.

Alternative 2: Using an actual tuple as key

If you really want to use tuples (instead of a composed single value), you can use:

a = [['a','b','c'],['d', 'e', 'g']]

b = dict()

for entry in a:
  b[(entry[0],entry[1])] = entry[2]

print(b)

This returns the following dictionary: {('a', 'b'): 'c', ('d', 'e'): 'g'}.

Upvotes: 0

mad_
mad_

Reputation: 8273

A simple dict comprehension

{(item[0],item[1]):item[2] for item in a}

Upvotes: 2

Related Questions