Using a Python Dictionary as a Key (Non-nested)

Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys?

The general problem with more complicated non-hashable objects and my specific use case has been moved here. My original description of my use case was incorrect.

If you have a really immutable dictionary (although it isn't clear to me why you don't just use a list of pairs: e.g. [('content-type', 'text/plain'), ('host', '')]), then you may convert your dict into:

  1. A tuple of pairs. You've already done that in your question. A tuple is required instead of list because the results rely on the ordering and the immutability of the elements.

    >>> tuple(sorted(a.items()))
  2. A frozen set. It is a more suitable approach from the mathematical point of view, as it requires only the equality relation on the elements of your immutable dict, while the first approach requires the ordering relation besides equality.

    >>> frozenset(a.items())

How to convert python nested dict to non-nested dict?, vote accepted. This is python package for flatten dictionary. You can use this + key if parent_key is not '' else key if isinstance(value, dict):  Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair. keys () method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary. Syntax: dict.keys () Parameters: There are no parameters.

If I needed to use dictionaries as keys, I would flatten the dictionary into a tuple of tuples.

You might find this SO question useful: What is the best way to implement nested dictionaries?

And here is an example of a flatten module that will flatten dictionaries:

I don't fully understand your use case and I suspect that you are trying to prematurely optimize something that doesn't need optimization.

Using a Python Dictionary as a Key (Non-nested), Using a Python Dictionary as a Key (Non-nested) - Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using  keys - Using a Python Dictionary as a Key (Non-nested) python dictionary methods (8) All hashable built in python objects have a.__hash__ () method. You can check for that.

One way to do this would be to subclass the dict and provide a hash method. ie:

class HashableDict(dict):
    def __hash__(self):
        return hash(tuple(sorted(self.iteritems())))

>>> d = HashableDict(a=1, b=2)
>>> d2 = { d : "foo"}
>>> d2[HashableDict(a=1, b=2)]

However, bear in mind the reasons why dicts (or any mutable types) don't do this: mutating the object after it has been added to a hashtable will change the hash, which means the dict will now have it in the wrong bucket, and so incorrect results will be returned.

If you go this route, either be very sure that dicts will never change after they have been put in the other dictionary, or actively prevent them (eg. check that the hash never changes after the first call to __hash__, and throw an exception if not.)

Using a Python Dictionary as a Key (Non-nested), Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? The general problem  In Python, a dictionary is an unordered collection of items. For example: dictionary = {'key' : 'value', 'key_2': 'value_2'} Here, dictionary has a key:value pair enclosed within curly brackets {}. To learn more about dictionary, please visit Python Dictionary.

To turn a someDictionary into a key, do this

key = tuple(sorted(someDictionary .items())

You can easily reverse this with dict( key )

FlatDict, nested dicts as a single level dict with delimited keys. flatdict supports Python API changes are indicated by the major version, non-breaking improvements  Dictionaries in Python are a list of items that are unordered and can be changed by use of built in methods. Dictionaries are used to create a map of unique keys to values. About Dictionaries in Python. To create a Dictionary, use {} curly brackets to construct the dictionary and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. Keys must be quoted, for instance: “title” : “How to use Dictionaries in Python”

Hmm, isn't your use case just memoizing function calls? Using a decorator, you will have easy support for arbitrary functions. And yes, they often pickle the arguments, and using circular reasoning, this works for non-standard types as long as they can be pickled.

See e.g. this memoization sample

Solved: Argument: A Non-nested List Of Objects Returns: A , Answer to Argument: a non-nested list of objects returns: a dictionary, where Where There Is A Key For Each Type Found, The Value Of Each Key Is A List In python create function where Advertising Choices · Cookie Notice · General Policies · Intellectual Property Rights · Terms of Use · Chegg Tutors Terms of Service  If you need to use the whole combination of key1 to keyn to get value, you can flip the dict like I suggested below for O(nk*nv) (number of keys * number of values) or use the tuple method above. Assuming you need to build the tuple on insertion and again when you need to get a value, both will be O(nk) where nk is the number of keys.

How to Remove Null/None Values From a Dictionary in Python, To clean the provided dictionary, each key-value pair will be examined. Given a Python dictionary, remove any term whose value is None If nested dictionaries are not a concern then a one-liner function using dictionary  Access nested dictionary items via a list of keys? Find all occurrences of a key in nested python dictionaries and lists; Traverse a nested dictionary and get the path in Python? Find all the keys and keys of the keys in a nested dictionary; Searching for keys in a nested dictionary; Python: Updating a value in a deeply nested dictionary; Is

dict-deep · PyPI, Simple functions to set or get values from a nested dict structure or in fact a deep structure of I generally do not like changing python dicts to enable dot notation, hence no available The getter to be used on the last step (with the last key). Prerequisite – Python dictionary A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.

Python, Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key Let's discuss certain ways to safely get the nested available key in dictionary. Just returns non-error None if any key is not present​. Python dictionary method keys() returns a list of all the available keys in the dictionary. Syntax. Following is the syntax for keys() method − dict.keys() Parameters. NA. Return Value. This method returns a list of all the available keys in the dictionary. Example. The following example shows the usage of keys() method.

  • The sort is necessary as python dictionaries are not ordered by default
  • This looks to me like a design problem. Can you give an example where it makes sense to use a dictionary as a key?
  • I think the function should take named tuples (or class instances) instead of nested dicts. You wouldn't have that problem then.
  • I guess you meant sorted, and it returns a generator so you need to make a list out of it.
  • Your exact use case sounds exactly like memoization. There are recipes for that, and one of your answers suggests it. If I am just not understanding, could you explain why you don't just use a memoize recipe?
  • +1: Good point on ordering. A dictionary can always be transformed to a frozenset because the keys must be unique, assuring each tuple will be preserved in the set. Elegant.
  • This is a nice solution which is more general than than the specific problem I posed, but doesn't this doesn't handle dictionaries within dictionaries.
  • Now moved this to a new question
  • Note that, Frozen set solution will not work, if the dict contains list or any other mutable object as values. For ex: a={'key1': 'val1', 'key2': ['val2', 'val3']}
  • +1: tuple( someDictionary.items() ) works really, really well for making a dictionary into an immutable key.