Questions tagged [dictionary]

A dictionary maps keys to values allowing efficient retrieval of values by keys. Use the [map-function] tag for mapping functions; use the [maps] tag for geography.

A dictionary (also known as map, associative array, or symbol table) in computer science is a data structure that maps keys to values such that given a key its corresponding value can be efficiently retrieved.

It is commonly implemented as a hash map which allow O(1) amortized lookup. Alternatively, they may be implemented as a sorted list, with lookup requiring a binary search and making the lookup O(log N) amortized instead.

When tagging a question with , be sure to tag it with the language being used as well.

In C++

std::map<Key, T, Compare, Allocator>: A sorted associative container that contains key-value pairs with unique keys.

In .NET

Dictionary<TKey, TValue>: Represents a collection of keys and values.

In Python

dict: Maps hashable keys to arbitrary objects.

In Java

Map<K, V>: An object that maps keys to values.

See also

Related tags: , , , , , ,


For questions about Mapping Functions over collections of data, use tag.

For questions about the Geographical maps i.e. for visual representation of area, please use tag

85558 questions
544
votes
8 answers

Creating a new dictionary in Python

I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . .. How do I create a new empty dictionary in Python?
leora
  • 188,729
  • 360
  • 878
  • 1,366
544
votes
7 answers

Why updating "shallow" copy dictionary doesn't update "original" dictionary?

While reading up the documentation for dict.copy(), it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says: The m.copy() method makes a shallow copy of the items…
user225312
  • 126,773
  • 69
  • 172
  • 181
544
votes
22 answers

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

For example I have two dicts: Dict A: {'a': 1, 'b': 2, 'c': 3} Dict B: {'b': 3, 'c': 4, 'd': 5} I need a pythonic way of 'combining' two dicts such that the result is: {'a': 1, 'b': 5, 'c': 7, 'd': 5} That is to say: if a key appears in both…
Derrick Zhang
  • 21,201
  • 18
  • 53
  • 73
538
votes
30 answers

How to pretty print nested dictionaries?

How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint(), but it did not work: import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint(mydict) I simply want an indentation ("\t") for each nesting,…
user248237
527
votes
6 answers

Converting dictionary to JSON

r = {'is_claimed': 'True', 'rating': 3.5} r = json.dumps(r) file.write(str(r['rating'])) I am not able to access my data in the JSON. What am I doing wrong? TypeError: string indices must be integers, not str
sheetal_158
  • 7,391
  • 6
  • 27
  • 44
522
votes
15 answers

Is there any advantage of using map over unordered_map in case of trivial keys?

A recent talk about unordered_map in C++ made me realize that I should use unordered_map for most cases where I used map before, because of the efficiency of lookup ( amortized O(1) vs. O(log n) ). Most times I use a map, I use either int or…
Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
517
votes
9 answers

Python Dictionary Comprehension

Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: l = [] for n in range(1, 11): l.append(n) We can shorten this to a list comprehension: l = [n for n in…
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
496
votes
7 answers

How to convert Map keys to array?

Lets say I have the following map: let myMap = new Map().set('a', 1).set('b', 2); And I want to obtain ['a', 'b'] based on the above. My current solution seems so long and horrible. let myMap = new Map().set('a', 1).set('b', 2); let keys =…
Lilleman
  • 7,392
  • 5
  • 27
  • 36
494
votes
14 answers

How can I avoid "RuntimeError: dictionary changed size during iteration" error?

Suppose I have a dictionary of lists: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} Now I want to remove key-value pairs where the values are empty lists. I tried this code: for i in d: if not d[i]: d.pop(i) but this gives an…
user1530318
  • 25,507
  • 15
  • 37
  • 48
491
votes
20 answers

Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' :…
Julio César
  • 12,790
  • 10
  • 38
  • 45
489
votes
11 answers

Get dictionary key by value

How do I get a Dictionary key by value in C#? Dictionary types = new Dictionary() { {"1", "one"}, {"2", "two"}, {"3", "three"} }; I want something like this: getByValueKey(string…
loviji
  • 12,620
  • 17
  • 63
  • 94
475
votes
4 answers

Passing a dictionary to a function as keyword parameters

I'd like to call a function in python using a dictionary with matching key-value pairs for the parameters. Here is some code: d = dict(param='test') def f(param): print(param) f(d) This prints {'param': 'test'} but I'd like it to just print…
Dave Hillier
  • 18,105
  • 9
  • 43
  • 87
464
votes
22 answers

When is del useful in Python?

I can't really think of any reason why Python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign None to it. And when deleting from a dictionary, a del…
Jason Baker
  • 192,085
  • 135
  • 376
  • 510
461
votes
36 answers

How to use a dot "." to access members of dictionary?

How do I make Python dictionary members accessible via a dot "."? For example, instead of writing mydict['val'], I'd like to write mydict.val. Also I'd like to access nested dicts this way. For example mydict.mydict2.val would refer to mydict = {…
bodacydo
  • 75,521
  • 93
  • 229
  • 319
460
votes
6 answers

Difference between map and collect in Ruby?

I have Googled this and got patchy / contradictory opinions - is there actually any difference between doing a map and doing a collect on an array in Ruby/Rails? The docs don't seem to suggest any, but are there perhaps differences in method or…
sscirrus
  • 55,407
  • 41
  • 135
  • 228