0

For the following data, how can i create a dictionary with id as the key and value of array of tuple [(x, y)]

  id  x  y
0  a  1  2
1  a  2  3
2  b  3  4

The expected dictionary is

{a: [(1,2), (2,3)], b:[(3,4)]}

1

2 Answers 2

1

When iterating over the table (however you are doing it) check if the id is already in the dict and append to the existing value or add the new key:

data = {}
for id,x,y in SOURCE:
    if id in data:
        data[id].append((x,y))
    else:
        data[id] = [(x,y)]
Sign up to request clarification or add additional context in comments.

Comments

1

The solution offered by @tadhg-mcdonald-jensen seems a perfect opportunity to take advantage of a defaultdict:

from collections import defaultdict

data = defaultdict(list)

with open(SOURCE_FILE_NAME) as source:
    for line in source:
        id, x, y = line.rstrip().split()
        data[id].append((x, y))

This avoids the decision to set or append -- simply append and let the defaultdict do the right thing for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.