Lostsoul
Lostsoul

Reputation: 25999

Storing more than one key value in a tuple with python?

I'm new to Python and still learning. I was wondering if there was a standard 'best practice' for storing more than one key value in a tuple. Here's an example:

I have a value called 'red' which has a value of 3 and I need to divide it by a number (say 10). I need to store 3 values: Red (the name), 3 (number of times its divides 10) and 1 (the remainder). There are other values that are similar that will need to be included as well, so this is for red but same results for blue, green, etc. (numbers are different for each label).

I read around and I think way I found was to use nested lists, but I am doing this type of storage for a billion records (and I'll need to search through it so I thought maybe nested anything might slow me down).

I tried to create something like {'red':3:1,...} but its not the correct syntax and I'm considering adding a delimiter in the key value and then splitting it but not sure if that's efficient (such as {'red':3a1,..} then parse by the letter a).

I'm wondering if there's any better ways to store this or is nested tuples my only solution? I'm using Python 2.

Upvotes: 0

Views: 3833

Answers (3)

Mark Byers
Mark Byers

Reputation: 838156

The syntax for tuples is: (a,b,c).

If you want a dictionary with multiple values you can have a list as the value: {'red':[3,1]}.

You may want to also consider named tuples, or even classes. This will allow you to name the fields instead of accessing them by index, which will make the code more clear and structured.

I read around and I think way I found was to use nested lists, but I am doing this type of storage for a billion records(and I'll need to search through it so I thought maybe nested anything might slow me down).

If you have a billion records you probably should be persisting the data (for example in a database). You will likely run out of memory if you try to keep all the data in memory at once.

Upvotes: 3

skb
skb

Reputation: 21

Perhaps you mean dictionaries instead of tuples?

{'red': [3,1], 'blue': [2,2]}

If you are trying to store key/value pairs the best way would be to store them in a dictionary. And if you need more than one value to each key, just put those values in a list.

I don't think you would want to store such things in a tuple because tuples aren't mutable. So if you decide to change the order of the quotient and remainder (1, 3) instead of (3,1), you would need to create new tuples. Whereas with lists, you could simply rearrange the order.

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93030

Use tuple. For example:

`('red', 3, 1)`

Upvotes: 1

Related Questions