Python and dictionary like object

I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary).

But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered bad, as I can read on almost every Pythonista's blog).

But duck typing is part of Python's philosophy, so how could I check if an object is dictionary-like?

Thanks!

Edit : Thank all for the answers. Just in case, the function I coded can be found at this place : http://blog.cafeaumiel.com/public/python/dict_deep_update.py


Asked by: Lucas180 | Posted: 30-11-2021






Answer 1

Check out the (new in 3.x) abstract base classes (ABC's) in the collections module:

http://docs.python.org/3.1/library/collections.html

I would consider checking with isinstance against Mapping like in the following:

>>> import collections
>>> isinstance({},collections.Mapping)
True

Then, if you make your own dict-like class, make collections.Mapping one of its bases.

The other route is trying and catching whatever exceptions for the dictionary operations, - but with the recursion you're talking about, I'd rather check against the base type first than handle figuring out what dict or subdict or other dict member was or was not there to throw an exception.

Editing to add: The benefit of checking against the Mapping ABC instead of against dict is that the same test will work for dict-like classes regardless of whether or not they subclass dict, so it's more flexible, just in case.

Answered by: Roland269 | Posted: 01-01-2022



Answer 2

use isinstance, there is nothing wrong with it and it's routinely used in code requiring recursion.

If by dictionary-like you mean the object's class inherit from the dict, isinstance will also return True.

>>> class A(dict):
    pass

>>> a = A()
>>> isinstance(a, dict)
True

Answered by: Walter645 | Posted: 01-01-2022



Answer 3

Duck typing is where you do what you want to do, and deal with the fallout if your objects don't behave the way you expected them to.

You want to check if something is dict-like, and update it if it is, right? Just call the object's update method, and handle the Exception you get if there is no such method.

Of course, this will fall flat if you deal with custom class objects which have update methods that do something else entirely -- I'm not quite sure how to deal with that.

Answered by: Owen739 | Posted: 01-01-2022



Answer 4

Well, to update recursively a dictionary, you must call the 'items' method to iterate on it.

So I suggest, you just do :

try :
    for key, value in data.items() :
         # recursive call
except AttributeError :
    # handling the trouble

Answered by: Melanie303 | Posted: 01-01-2022



Answer 5

If you also have to handle custom classes that behave like dictionaries but aren't subclassed from dict, you can use getattr to get the function you require.

# loop
# ... more code
someObject = getObject(..)
try:
    getattr(someObject, "update")("someValue")
except AttributeError:
    # Wasn't a type we can handle

Answered by: Elise409 | Posted: 01-01-2022



Answer 6

I like to check for the '__setitem__' magic method... this that is what allows the foo['bar'] = baz behavior.

if getattr(obj, '__setattr__'):
    obj[key] = val

Here is the python 2.7 docs

Answered by: John692 | Posted: 01-01-2022



Similar questions

python - Why is dictionary in object not different from the other?

I have the following Python code: #!/usr/bin/env python2.6 class container(object): name = 'container' configuration = {'var1': 'var1', 'var2': 'var2'} if __name__ == "__main__": container1 = container() container2 = container() container2.name = 'container2' container2.configuration['var2'] = 'newvar2' print container1.name print container1.configu...


python - How to check a dictionary for a class object value?

I have a dictionary, named descendDict And it contains 4 keys which are class objects, which have values that are both letters and other class objects. Now what I'm trying to do is sort through the dictionary, and call out different actions if the value brought up in the dictionary is a class object, or if it is a letter: for x in descendDict: print x, descendD...


Python - using a dictionary item as a object

I am trying to make arguments easier to manage in a script I am putting together, I figured I'd wrap a bunch of related items into a dictionary, and pass the dictionary out of the func. pulling out the objects as I need them. One of these items is a regEx, and I'm struggling to figure out how to structure things properly so I can make it work. In my initial code (no dictionary). I am 'hard' coding the reg...


Python Object as Dictionary Value


python object in dictionary

I am trying to save the object candle in the dictionary candlebuffer, however it gives me the error below. I am struggling; what is incorrect with my syntax? class Observer: def __init__(self): self.listeners = [] def attach(self, listener): if not listener in self.listeners: self.listeners.append(listener) def notify(self, event): ...


python dictionary object vs value

i am still not quite familiar with the programmation language and i am struggling to understand the difference between low_price which returns a value and high_price which returns (apparently) an object. Can someone explain me why they have different structure? Both are dictionary. high_price is getting through a function. Hope it makes sense. Apologies if the indentation isnt correct, i am still struggling to get this rig...


python - How to save a dictionary having value as an object

binHow to save this kind of dictionary in mongiengine. {'xnFH8XCJiwMRFu8A': <dropbox.session.OAuthToken object at 0x2e4efd0>, '867s6bnwbg3kc':<dropbox.session.OAuthToken object at 0x2e50610>} I am trying to save the dropbox access token. Thanks for the help in advance. Thanks for the help. But getting the error InvalidStringData. No idea where I am do...


dictionary - Is Python dict an Object?

I have a dict like this: >>> my_dict = {u'2008': 6.57, u'2009': 4.89, u'2011': 7.74, ... u'2010': 7.44, u'2012': 7.44} Output with has_key: >>> my_dict.has_key(unicode(2012)) True Output with hasattr: >>> hasattr(my_dict, unicode(2012)) False I co...


python - How to add dictionary to json object

In my construct below, I am trying to pass a JSON object through my web service. As a new requirement I have to pass a dictionary object which is sent in the code below. Can you please guide me how to add the dictionary to JSON object? if plain_text is not None: blob = TextBlob(plain_text) sentiment = TextBlob(plain_text) sent = {} for sentence in blob.sentences:...


python - Save dictionary to model object

I have a dictionary like this one: {'company_name': 'Google', 'title': 'headline', ...} I know that i can store the values using this way: user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...) However this is not good if I have many form fields. There is any way to do this without hard code all the maps? The key val...


How do I use a python dictionary object in MATLAB?

I'm playing with the new capability in MATLAB 2014b where you can call python directly from matlab and get python objects in the workspace (like you've been able to with Java for a long time). I have successfully called a function and gotten a dictionary into the workspace, but I'm stuck on how to harvest the values from it. In this case I have a dictionary full of dictionaries, so I can't just convert it to MATLAB cells ...


Python Object as list in dictionary

I am in python and I have this: places = [{'placeId':5},{'placeId':2}] and this(note that the workout has a lot more data than 'To' and 'Exercise'.. I didnt wrote them all): workout={'To': 'John' , 'Exercise': 'pull-ups'} and I want to make this: Emailwork={'To': 'John' , 'Exercise': 'pull-ups', 'places':[5,2]} Can I have ...


python - Add object to start of dictionary

I am making a group chatting app and I have images associated with the users, so whenever they say something, their image is displayed next to it. I wrote the server in python and the client will be an iOS app. I use a dictionary to store all of the message/image pairs. Whenever my iOS app sends a command to the server (msg:<message), the dictionary adds the image and message to the dictionary like so:


python - Dictionary key from object field

I want to use an object as a key in a dictionary, but I want to lose the identity of the key to that of one of the object's fields. Overloading the hash and equality functions is trivial, and works as expected, but I was not able to find a solution for the key to be inserted with the field's type inside the dictionary. Here is an example: class Foo: def __init__(self, val): self.val = va...


python - How to add a new entry into a dictionary object while using jinja2?

I am not able to append add a new entry into a dictionary object while using jinja2 template. For example, here I am using jinja2 template and I have created a data variable which is a dictionary. And after checking some if condition I WANT to append location attribute to the data object e.g. {%- set data = { 'name' : node.Name, ...


python - Cannot save object to dictionary

I'm trying to analyse the time difference between any given 2 stages of an online order being sent to restaurant. Here is an overview of what I'm trying to do: Iterate through a list of dictionary objects Take the difference between two datetime values as total seconds Save that difference to another dictionary, using order identifier as key, and total seconds difference as value ...


python - Can I read a file object into a gensim Dictionary class?

The gensim Dictionary object keeps track of the vocabulary of the collection of documents (aka corpus). But to feed the data into the object, the data has to be fed into the memory, e.g. import io from gensim.corpora import Dictionary infile = '/path/to/data' with io.open(infile, 'r', encoding='utf8') as fin:...


python - Try to query from dictionary object

I was trying to get query result form mysql. def on_get(self, req, resp): try: db = MySQLdb.connect(**db_conf.dbConfig) #use dictionary cursor cursor = db.cursor(MySQLdb.cursors.DictCursor) q = ("select * from BUDGET") cursor.execute(q) rows = cursor.fetchall() #init the output object output = {'budget': []} for row in rows: ...


Python Dictionary JSON object

I am making a get request as shown below: testHeaders = {'X-Api-Key':'myAPIKey'} testURL = 'https://api.mytest.com/v2/test.json' r = requests.get(testURL, headers=testHeaders) status = r.status_code response = r.json() My response returns a dictionary object with two keys and then multiple values inside each key. How can I assign each of these keys and then access and assess the d...


class - How to get python dictionary as an object with snmp OID as key

I'm trying to pass a dictionary which has key as SNMP OID and value as dictionary with some values: d = {'1.3.6.1.6.3.1.1.5.1': {'text':"something","help":'somethingelse','param':1}, '1.3.6.1.6.3.1.1.5.2':{'text':"something for this oid","help":'somethingelse_for this','param':2} , and so on for other 1000 snmp OIDs } Now I want to pass this dictionary to a class to convert it to...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python, dictionary and int error

I have a very frustrating python problem. In this code fixedKeyStringInAVar = "SomeKey" def myFunc(a, b): global sleepTime global fixedKeyStringInAVar varMe=int("15") sleepTime[fixedKeyStringInAVar] = varMe*60*1000 #more code Now this works. BUT sometimes when I run this function I get TypeError: 'int' object does not support item assignment


python - Best way to create a NumPy array from a dictionary?

I'm just starting with NumPy so I may be missing some core concepts... What's the best way to create a NumPy array from a dictionary whose values are lists? Something like this: d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } Should turn into something like: data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] ...


python - List a dictionary

In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class ...


python - How to filter a dictionary by value?

Newbie question here, so please bear with me. Let's say I have a dictionary looking like this: a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} I want all values that are equal to each other to be moved into...


python - Remove dictionary from list

If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).


C# way to mimic Python Dictionary Syntax

Is there a good way in C# to mimic the following python syntax: mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # &lt;-- This line mydict["te"] = "5"; # &lt;-- While also allowing this line In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set. I've been trying to work...


python - Can a dictionary be passed to django models on create?

Is it possible to do something similar to this with a list, dictionary or something else? data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) Even better if I can extend it: Model.objects.create(data_dict, extra='hello', extra2='world')


python - Make Dictionary From 2 List

This question already has answers here:


Python dictionary simple way to add a new key value pair

Say you have, foo = 'bar' d = {'a-key':'a-value'} And you want d = {'a-key':'a-value','foo':'bar'} e = {'foo':foo} I know you can do, d['foo'] = foo #Either of the following for e e = {'foo':foo} e = dict(foo=foo) But, in all these way to add the variable foo to dict, I have had to use the word foo twice; onc...


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


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: &gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}


python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top