0

According to https://www.tutorialspoint.com/python/python_dictionary.htm I should be able to add a property to a dictionary quite easily, however the hasattr function does not seem to notice any change on the dictionary:

obj = {}
obj["foo"] = "bar"
print hasattr(obj, "foo") # prints False

Why is this, and is there a workaround?

BRNTZN
  • 564
  • 1
  • 7
  • 21
  • 2
    do you mean `'print 'foo' in obj`? – Ma0 Jun 07 '17 at 11:56
  • 1
    You're adding an item under a key to a dictionary, not a property. – Ilja Everilä Jun 07 '17 at 11:57
  • @IljaEverilä what is the difference, and then how do I add a property? – BRNTZN Jun 07 '17 at 11:58
  • 1
    See https://stackoverflow.com/questions/10724766/pythons-hasattr-on-list-values-of-dictionaries-always-returns-false, for example. And you probably don't want to add properties to dict, really. It is meant for storing values under keys. Do you happen to have a Javascript background? A property is something the object has. On the other hand collections contain items, and a dict is a collection of key, value pairs of sorts. Think Maps in Java. – Ilja Everilä Jun 07 '17 at 12:00
  • @IljaEverilä Haha yeah js and java, I think that's messing me up here. – BRNTZN Jun 07 '17 at 12:01

1 Answers1

2

You haven't added a property, you've added a key, which is what dictionaries are for.

The way to tell it a key exists in a dict is to use in:

print("foo" in bar)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895