Is There Such Thing As An Immutable Dictionary And What About Constants In Python

I know an immutable list is a tuple and a set is frozenset. Is it possible to have an immutable dictionary? I know you can make constants with const in Javascript but what about in Python?

keys in a dictionary are immutable the value is mutable.

https://docs.python.org/3.9/reference/datamodel.html#object.hash

https://docs.python.org/3.9/library/functions.html#hash

Here’s a good explanation:
https://stackoverflow.com/questions/15439134/why-should-dictionary-keys-be-immutable

And here:
https://stackoverflow.com/questions/15370081/how-net-dictionary-implementation-works-with-mutable-objects/15370321#15370321

I mean what if you wanted a immutable dictionary with the keys immutable and the values also.

Edit: Sorry, I haven’t had enough coffee yet.

now I see what you’re saying. Dictionaries are mutable…but only the values. Keys are immutable objects b/c they have a hash value.

See:
https://docs.python.org/3.9/library/stdtypes.html#dict

And here in the documentation:
https://docs.python.org/3.9/glossary.html#term-hashable

1 Like

If you wanted to make it so that you were getting this

my_immutable_dict = { 
    "A" : "b",
    "c" : "D"
}

my_immutable_dict["e"] = "F" #OK
print(my_immutable_dict) # {'A': 'b', 'c': 'D', 'e': 'F'}

my_immutable_dict["A"] = "G" # Error: Can't change value
print(my_immutable_dict) # {'A': 'b', 'c': 'D', 'e': 'F'}

you have two choices that I can think of right now:

  1. Subclass the dict object and override the appropriate method.

  2. Create your own dict-like object which behaves how you want.

3 Likes

For my own understanding…
Why would one want to do that? Is there a real world case scenario for it?

If you had a hardcoded dictionary that you knew shouldn’t be changed during runtime, I’d guess it could be useful to make it immutable for security reasons. Similar to how it’s best practice to declare variables as constants in JS if they don’t need to be changed.

Just spit balling though, I could be completely wrong.

1 Like

No idea. I can’t immediately think of a reason why you’d need a completely immutable dict

OP asked whether it could be done, not whether it should be done… :smiley:

As it happens...

…I wanted to see whether it was, indeed, possible.

I’ve got a rudimentary implementation in less than 10 lines. Fails on some cases, though, but it’s kinda there.

2 Likes

I don’t need it to be immutable but if never has to change then maybe go with it.

I don’t really know how to do the first and second things. For the first one, what method do you override, it’s probably a dunder/magic method. What kind of dict like object should it be. If create a very good one then maybe can I add it to an existing module or create a module myself. How to I create my own module and share it to different sources. I have seen a thing that has the code for the collections module.

That’s good but what if I wanted this:

my_immutable_dict = { "A" : "b", "c" : "D" } my_immutable_dict["e"] = "F" #Error print(my_immutable_dict) # {'A': 'b', 'c': 'D', 'e': 'F'} my_immutable_dict["A"] = "G" # Error: Can't change value print(my_immutable_dict) # {'A': 'b', 'c': 'D', 'e': 'F'}

I mean a one that is completely immutable which means you can’t add new keys and change values to it.

I should make sure if that’s right. Give me an example(code) showing me that’s right.

… I (wrongly) assumed that the Python 3 material covered the concept of class inheritance. :man_facepalming: Turns out, the Python 2 course does go over inheritance (and by extension, how to base classes off other classes) but not the Python 3 one…

I’d suggest that you do this module from the Py2 course which will go over inheritance and some - quite frankly - fundamental concepts for classes.

(Why this isn’t in the Py3 stuff, I have no idea…)

That would be entirely up to you, depending on what you wanted the new class to do etc.

Ok, I misunderstood the extent to which you wanted the instance to be immutable. My previous answer remains valid, though.

…or you could write some code to verify it yourself… y’know, as a learning exercise? :slight_smile:

4 Likes

No, I’m not doing it. Even though the Learn Python course didn’t cover it(I checked but it wasn’t there), in the Learn Intermediate Python 3 course here there was maybe about 4 - 5 exercises about inheritance: 2nd exercise(https://www.codecademy.com/courses/learn-intermediate-python-3/lessons/int-python-oop/exercises/inheritance) to 6th exercise(https://www.codecademy.com/courses/learn-intermediate-python-3/lessons/int-python-oop/exercises/multiple-inheritance). Also the link you showed me is Python 2. I visited the link but I didn’t do it and the code looks strange:
script.py:

class Fruit(object):
  """A class that makes various tasty fruits."""
  def __init__(self, name, color, flavor, poisonous):
    self.name = name
    self.color = color
    self.flavor = flavor
    self.poisonous = poisonous

  def description(self):
    print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)

  def is_edible(self):
    if not self.poisonous:
      print "Yep! I'm edible."
    else:
      print "Don't eat me! I am super poisonous."

lemon = Fruit("lemon", "yellow", "sour", False)

lemon.description()
lemon.is_edible()

(In Python 2).
Why do we have to put object as an argument to the top line of the code?
What does this do?

print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)

Is this valid in Python 3? It doesn’t have the brackets and treats print as a statement. I have seen the % in strings but what is it? It’s older than f strings and also requires more typing. Python 2 is actually a bit different than Python 3. Why is this not a comment and a string:
"""A class that makes various tasty fruits."""
Is there such thing as multi line comments in Python 3? I’ve heard of multi line comments in other languages. If there isn’t such thing then can I add the new feature to Python. How can I do that?

Yes.

Multi-line strings on their own (as you can see in the code you posted) are Python’s version of multi-line comments:

"""
this is a
multi-line comment
"""
print("""
This is not a comment.
It will be printed with
Formatting intact
""")

In Python 2, print is not a function, it is just a statement (like return).


That is a way of string formatting. This article gives a good explanation of it.


The class Fruit (object) is inheritance in Python. It means the Fruit class inherits from the object class.

1 Like

Yes, and in the Python 3 course the inheritance is implied when doing this:

class Fruit:
    ....

Still inherits from the base object class, but you don’t necessarily need to specify that. :slight_smile:

1 Like

The object class is new to me. Tell me more about the object class in Python. When I was experimenting(working with the type() function), I saw the base of all the built in data types that I experimented in that time was type. I’m going to read this article you suggested me:

.
When I quoted the link it didn’t come as a link just text like other previous times. Why this?

To make text linked on the forums, you just put:

[random text](https://www.somerandomurl.com)

Let me try…:
[random text] (https://www.somerandomurl.com)
Is that site all about you?

What about that?

No, that was just an example URL, aslo if you want the text to appear hyperlinked, you can’t have a space between the ] and the (.


I’m not entirely sure, but I think it is just the base type of everything; everything inherits from object, but don’t take my word for it (thepitycoder would be the one to properly answer your question).

There’s an explanation in the documentation, for the object class as well as coverage of classes and inheritance in their tutorial material which mentions that all classes come from the base object.

If in doubt, refer to the docs. :slight_smile:

1 Like

A few months ago(about 2 months), I did the classes module(from Learn Python 3) and there was inheritance and polymorphism. But now, I see it’s gone. It’s probably gone because it’s in the Learn Intermediate Python 3 course.