Skip to main content
79 votes

When to use a dictionary vs tuple in Python

I would use a namedtuple: from collections import namedtuple Filesize = namedtuple('Filesize', 'filename size') file = Filesize(filename="blabla", size=123) Now you can use file.size and file....
Doc Brown's user avatar
  • 209k
45 votes
Accepted

Why should I use namedtuple over SimpleNamespace when not using dict, they seem very similar

SimpleNamespace is basically just a nice facade on top of a dictionary. It allows you to use properties instead of index keys. This is nice as it is super flexible and easy to manipulate. The ...
unholysampler's user avatar
35 votes

Is there a better way to use C# dictionaries than TryGetValue?

Some good answers here on the general principles of hashtables/dictionaries. But I thought I'd touch on your code example, int x; if (dict.TryGetValue("key", out x)) { DoSomethingWith(x); } As ...
David Arno's user avatar
  • 39.3k
30 votes
Accepted

Is there a better way to use C# dictionaries than TryGetValue?

Dictionaries (C# or otherwise) are simply a container where you look up a value based on a key. In many languages it's more correctly identified as a Map with the most common implementation being a ...
Berin Loritsch's user avatar
19 votes

When to use a dictionary vs tuple in Python

{"filename": "blabla", "size": 123}, or just ("blabla", 123) This is the age old question of whether to encode your format / schema in-band or out-of-band. You trade off some memory to get the ...
candied_orange's user avatar
17 votes

Is there a better way to use C# dictionaries than TryGetValue?

This is neither a code smell nor an anti-pattern, as using TryGet-style functions with an out parameter is idiomatic C#. However, there are 3 options provided in C# to work with a Dictionary, so ...
BrianH's user avatar
  • 6,122
15 votes
Accepted

Why are there two ways to retrieve values from a dictionary in Python?

Though I was not involved into the design of Python, I think I can make an educated guess: dictionary["key"] is shorter and very convenient to use, since it is consistent with access to ...
Doc Brown's user avatar
  • 209k
13 votes
Accepted

Is there a term used for the collection of a key and value in a C# dictionary?

This is known, simply, as a Key-Value Pair. You can see it when iterating over a Dictionary with foreach - each resulting object in the loop is of type KeyValuePair<K,V>.
Avner Shahar-Kashtan's user avatar
13 votes

Is there a better way to use C# dictionaries than TryGetValue?

There are at least two methods missing from C# dictionaries that in my opinion clean up code considerably in a lot of situations in other languages. The first is returning an Option, which lets you ...
Karl Bielefeldt's user avatar
10 votes

Why are Python sets and dictionaries not ordered by default?

You are correct that item are store internally with some order, but this internal order is determined by the hash code of the key, which is what allows retrieval to be so fast. So if a set/dict should ...
JacquesB's user avatar
  • 59.8k
9 votes
Accepted

What is the difference between the solution that uses defaultdict and the one that uses setdefault?

The key line is this one: d.setdefault(t, []).append(word) return d d.setdefault is just a function. That function is receiving two arguments: t, and a new list. Both of those arguments are ...
David's user avatar
  • 206
9 votes

Why are Python sets and dictionaries not ordered by default?

Your premise is incorrect. As of Python 3.6, dicts remember their insertion order. This was an implementation detail, and was promoted to full language feature in 3.7. In 3.6, for the specific case ...
Kevin's user avatar
  • 2,658
8 votes
Accepted

Why can't Dictionary(TKey, TValue) update it's hashcodes?

Why doesn't the Dictionary class have logic to move an object to the correct bucket when it detects that the object's hashcode has changed? Just to be sure, we are talking about the hash of the key ...
dagnelies's user avatar
  • 5,475
8 votes

Is there a better way to use C# dictionaries than TryGetValue?

That's 4 lines of code to essentially do the following: DoSomethingWith(dict["key"]) I agree that this is inelegant. A mechanism that I like to use in this case, where the value is a struct ...
Eric Lippert's user avatar
  • 46.2k
7 votes

Why is there no key specified with .NET KeyNotFoundException?

This may not be the official answer, but... C# and VB.NET - the main .NET languages - are statically typed languages(yea, I know, they support dynamic typing, but still). This means properties in ...
Idan Arye's user avatar
  • 12.1k
7 votes
Accepted

Do you name a dictionary by the key or the value?

That depends, but generally I'd suggest naming by the values. The keys are often just a way to quickly find what you are actually looking for and will be using. Depending on context, for your ...
rjnilsson's user avatar
  • 409
7 votes
Accepted

API Design: Should I use strings or an enum for dictionary keys

How is the API exposed? Through an ordinary .NET interface, or through REST or similar? In the first case, enums are a good choice if you have a limited amount of accepted values. You can check valid ...
Arseni Mourzenko's user avatar
7 votes

When to use a dictionary vs tuple in Python

I would use a class with two properties. file.size is nicer than either file[1] or file["size"]. Simple is better than complex.
JacquesB's user avatar
  • 59.8k
6 votes
Accepted

Why are Python sets and dictionaries not ordered by default?

The point is not that the overhead is particularly large, more that it is there at all. Language features must always strike a balance of cost-effectiveness. Dictionaries are absolutely fundamental ...
Kilian Foth's user avatar
6 votes

Why can't Dictionary(TKey, TValue) update it's hashcodes?

Short answer: Dictionary can't detect that some hashcode changed. There is no event that it can subscribe to. Getting hashcode is just a call to Object.GetHashCode(). That method is called once when ...
Sergey Kovalev's user avatar
6 votes

Pointers vs keeping indices of objects stored in a central (associative) array?

Is it correct that for the reasons I outlined above avoiding references and embracing ids of objects is considered the preferred approach? If you want to implement a save button in your game, you ...
Diane M's user avatar
  • 2,076
6 votes

Query language for python dictionary

Don't eval() unless the user is entirely trusted. Instead, implement a simple language for such conditionals. For example, we can define a data model that represents the structure of a logical ...
amon's user avatar
  • 135k
5 votes

When to use a dictionary vs tuple in Python

Are the filenames unique? If so, you could scrap the list entirely and just use a pure dictionary for all the files. e.g. (a hypothetical website) { "/index.html" : 5467, "/about.html" : 3425,...
user949300's user avatar
  • 8,859
5 votes

Why is there no key specified with .NET KeyNotFoundException?

This question involves digging into the history of .NET Framework design. As such, People who actually worked in the .NET Framework design team would be able to provide authoritative first-hand ...
rwong's user avatar
  • 16.9k
5 votes
Accepted

Is polymorphism appropriate for modeling natural language form (structure), or is there something better?

Completely reviewed answer following the edit of the question. Linguistic and language processing issues It would be very challenging to identify common properties and behaviors of adjectives, that ...
Christophe's user avatar
  • 78.4k
5 votes

Why can't Dictionary(TKey, TValue) update it's hashcodes?

Why doesn't the Dictionary class have logic to move an object to the correct bucket when it detects that the object's hashcode has changed? Because that defeats the object of a dictionary. The whole ...
David Arno's user avatar
  • 39.3k
5 votes

Why can't Dictionary(TKey, TValue) update it's hashcodes?

If the hash code of the key can change, then the keys can change, and keys that were different can become equal. And now you have a dictionary with equal values and a serious problem.
gnasher729's user avatar
  • 45.9k
5 votes
Accepted

What is the space complexity of a Python dictionary?

Space complexity is a property of algorithms, not of data-structures. And your assumption that the dictionary has a (large) fixed size would imply that it is O(1). It doesn't start with the maximum ...
Caleth's user avatar
  • 11.4k
4 votes
Accepted

Dictionary of dictionaries design in C#

There may be a simpler way towards it. Consider this: public class NAryDictionary<TKey, TValue> : Dictionary<TKey, TValue> { } public class NAryDictionary<...
YSharp's user avatar
  • 888
4 votes

Why should I use namedtuple over SimpleNamespace when not using dict, they seem very similar

I really like the answer about structured versus not, so I'm just providing a concrete example below. SimpleNamespace will accept keys that begin with _. If you're looking for a quick and easy way to ...
Alex Moore-Niemi's user avatar

Only top scored, non community-wiki answers of a minimum length are eligible