How-to articles, tricks, and solutions about DICTIONARY

How does collections.defaultdict work?

collections.defaultdict is a subclass of the built-in dict class in Python.

How to copy a dictionary and only edit the copy

There are a few ways to copy a dictionary in Python, depending on the level of copying that you need.

How to directly initialize a HashMap in Java?

To directly initialize a HashMap in Java, you can use the put() method to add elements to the map.

How to print a dictionary's key?

To print the keys of a dictionary in Python, you can use the built-in keys() method.

How to return dictionary keys as a list in Python?

In Python, you can use the dict.keys() method to return a view object that contains the keys of a dictionary.

How to sort a Map<Key, Value> by values in Java

To sort a Map&lt;Key, Value&gt; by values in Java, you can create a custom comparator that compares the values and pass it to the sort() method of the Map.Entry class.

I'm getting Key error in python

A KeyError in Python is raised when a dictionary key is not found in the dictionary.

Iterating over dictionaries using 'for' loops

To iterate over a dictionary using a for loop, you can use the .items() method to get a list of the dictionary's keys and values, and then iterate over that list.

Java - How to create new Entry (key, value)

To create a new key-value pair in a Map in Java, you can use the put method.

Python list of dictionaries search

Here is a code snippet that demonstrates how to search for a specific value in a list of dictionaries in Python:

Reverse / invert a dictionary mapping

Here's an example of how you can reverse or invert a dictionary mapping in Python:

Should I use 'has_key()' or 'in' on Python dicts?

It is recommended to use the in keyword to check if a key exists in a Python dict, rather than the has_key() method.

What is the difference between dict.items() and dict.iteritems() in Python2?

In Python 2, dict.items() returns a list of the dictionary's key-value pairs, whereas dict.iteritems() returns an iterator over the dictionary's key-value pairs.

1 2