Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: When to use dict, when list of tuples?

I have ids of jail prisoners, for example. Each prisoner has a name.

I know how dictionarys work and I know how tuples work and I know how lists work, but sometimes I see a dictionary being used, and sometimes a list of tuples. Which one should I use in my case?

d = {
    1: "Mike",
    2: "Bob",
    3: "Tom"
}

vs

l = [
    (1, "Mike"),
    (2, "Bob"),
    (3, "Tom")
]

And to generalize the question: WHEN should I use a dict, and when should I use a list of tuples, what are the benefits of one?

like image 467
Patrik Lippojoki Avatar asked Jan 20 '13 11:01

Patrik Lippojoki


People also ask

Why should you use a dict instead of a list or a tuple?

Dictionary is unordered collection. List and dictionary objects are mutable i.e. it is possible to add new item or delete and item from it. Tuple is an immutable object. Addition or deletion operations are not possible on tuple object.

Why use a dictionary instead of a list in Python?

Therefore, the dictionary is faster than a list in Python. It is more efficient to use dictionaries for the lookup of elements as it is faster than a list and takes less time to traverse. Moreover, lists keep the order of the elements while dictionary does not.

Should I use tuple or dictionary?

A tuple can contain different values with different datatype while a dictionary can contain only one datatype value at a time. Tuples are particularly useful for returning multiple values from a function.

Which is faster list tuple or dict?

It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.


1 Answers

You should use a list when it makes sense to store items in order. In this case it only matters that ID's are mapped to names.

A dictionary is a mapping, which means the relation between keys and values is not symmetrical. For example, it's tricky (and not always possible in the general case) to fetch a key by known value, whereas it's equally easy to filter a list (or a set, for that matter) of tuples by value of any of their items.

That being said, when choosing the data structure, it makes sense to consider how you are going to retrieve data from it. If you can see id and name as equal parts of something resembling a C struct (e.g. you'll need to search by any of them, etc.) then you're better off using a tuple or a collections.namedtuple. You can still put them in a list or a set depending on your need to keep it ordered.

But if id is a "special" field that is used to retrieve the rest of the info about the object, and it's guaranteed to be unique (well, "ID" means it), and you don't need internal order, and you want constant time random access -- of course use a dict.

like image 124
Lev Levitsky Avatar answered Oct 08 '22 05:10

Lev Levitsky