Is there a more elegant way to write this in Python? - python

I want to append 'status' to the dict value indexed by 'update_fields' or add ['status'] as a value to kwargs indexed by 'update_fields' if that key isn't present.
kwargs.setdefault('update_fields', kwargs.get('update_fields', []).append('status'))
It's either this or about 3 lines of code, surely python can do better than this!

get and setdefault are essentially two methods of doing the same thing; putting them together is repeating yourself. The only difference between get and setdefault is that setdefault sets the value if the default doesn't exist. After that, they are identical semantically.
So this part:
kwargs.get('update_fields', [])
..is redundant. setdefault sets the default (and returns it, like get) if the dictionary doesn't have a value for that key yet, otherwise it just looks up the value associated with the key.
So all you need is:
kwargs.setdefault('update_fields', []).append('status')

You don't need the kwargs.get() bit, setdefault only sets the value if it's not already there, you can just write:
kwargs.setdefault('update_fields', []).append('status')

Related

What's the shorter version for python dict checking key exist then get value?

if key in dict and dict[key]==value:
For the above, if statement, we first need to check the key that exists in dict then get the value. I'm curious do we have a shorter version or a better way for this?
Use dict.get(). It will return None if the key doesn't exist rather than raising an exception.
if dict.get(key) == value:
This will work as long as None isn't an actual value you might be comparing with, because you can't tell the difference between it being returned by default or from the dictionary. In that case, you need to provide some value that isn't a possible value. You could provide an empty object, since that creates a new list that can't be the same as one in the dictionary.
if dict.get(key, object()) == value:

Delete an item from a python dictionary when two keys have the same value

I have a python dictionary which has two keys with the same value.
mydict = {'a':'hi','b':'bye','c':'hi'}
What do I do if I want to delete just the element 'c':'hi'
I tried both del mydict['c'] and mydict.pop('c',None). Both these give me a KeyError.
First of all, there won't be a difference when you assign the same value to multiple keys. All elements in a python dict are required to have unique, immutable keys but there is no such constraint on the value. So don't worry too much about that!
This aside, both of the options you proposed behave as intended. The KeyError being thrown means that the key 'c' is not present in the dictionary. This leads me to believe that what you have shown is not in the dictionary at the time when the del or pop is called.

Python - If value in dictionary then

Here's my code
if "value" not in dictionary():
do something
else:
do something else
I get the error 'TypeError: 'dict' object is not callable.
I've tried changing the first line to
if dictionary["value"]:
But get a different error. Where am I going wrong here?
Assuming dictionary is in fact a dict() composed of key-values then it would be
if 'value' not in dictionary:
...etc
The error is essentially telling you that you are erroneously attempting to call a non-callable object as if it were a method/function.
If you are not particularly interested in whether or not a value exists you may use a method I am personally a fan of:
some_value = dictionary.get('value', 'valueIfNotPresent')
do_something(some_value)
The above allows you to provide a sentinel value (which is provided when the key does not exist). This can help with branch elimination (e.g. not having to if/else it, just allowing your code to act upon the sentinel) or at least reduce logic in checking for the existence of a key (unless the absence of a key is important).
Both are quite readable however and your mileage may vary.
EDIT:
#user1857805 is correct, if you are attempting to find out if a value is in a dictionary then the above (while still good and valid to know) is not enough. You will need to get the .values() as a list from the dictionary; however, as a dictionary may contain dictionaries you will need to recurse the dictionary to find all of the possibly stored values.
try using the following:
if 'value' not in dictionary.values():
do something
else:
do something else.

Does the order of keys in dictionary.keys() in a python dictionary change if the values are changed?

I have a python dictionary (say dict) in which I keep modifying values (the keys remain unaltered). Will the order of keys in the list given by dict.keys() change when I modify the values corresponding to the keys?
No, a python dictionary has an ordering for the keys but does not guarantee what that order will be or how it is calculated.
Which is why they are not guaranteed to be ordered in the first place.
The values stored in the dictionary do not have an effect on the hash values of the keys and so will not change ordering.
Taken from the Python Documentation:
The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.
No, the order of the dict will not change because you change the values. The order depends on the keys only (or their hash value, to be more specific at least in CPython). However, it may change between versions and implementations of Python, and in Python 3.3, it will change every time you start Python.
Python dictionaries' key ordering should not be assumed constant.
However, there are other datastructures that do give consistent key ordering, that work a lot like dictionaries:
http://stromberg.dnsalias.org/~strombrg/treap/
http://stromberg.dnsalias.org/~strombrg/red-black-tree-mod/
BTW, you should not name a variable "dict", because there is a builtin type called "dict" that will be made invisible.

List of dictionaries: get() schould loop over list

I know it is easy to implement.
I want a dictionary like class, which takes a list of dictionaries in the constructor.
If you read from this dict by key, the dict-class should check the list of dictionaries and return the first value. If none contains this key KeyError should be thrown like a normal dict.
This dictionary container should be read only for my usage.
You seem to be describing collections.ChainMap, which will be in the next version of Python (3.3, expected to go final later this year). For current/earlier versions of Python, you can copy the implementation from the collections source code.
Not really answer to the question: what if you just define method that merge all dictionaries into one? Why make new class for it?
How to merge: How to merge two Python dictionaries in a single expression?
Varargs: Can a variable number of arguments be passed to a function?
You can easily implement this with this logic.
Iterate over all the dictionaries in the list.
For each dictionary, see if it has the required key by using key in value statement.
If value is found, return the value from the function.
If you have iterated over all dictionaries, and value is not found, Raise KeyError exception.

Categories

Resources