I came across a Python script that contained:
{'__others__': None}
This was assigned to a variable. I want to know what it does; can someone tell me, or direct me to somewhere where I can learn it myself?
That dictionary has no special meaning in Python. It is just a dictionary with a string key and None as the value.
Without more context it is impossible to tell why that codebase is using __others__ as a key, but as long as it remains just a key in a dictionary then it'll never amount to anything more than just another string key.
It is probably a special value chosen not collide with other strong keys to be stored.
Related
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:
Similar to this question: Tuple declaration in Python
I have this function:
def get_mouse():
# Get: x:4631 y:506 screen:0 window:63557060
mouse = os.popen( "xdotool getmouselocation" ).read().splitlines()
print mouse
return mouse
When I run it it prints:
['x:2403 y:368 screen:0 window:60817757']
I can split the line and create 4 separate fields in a list but from Python code examples I've seen I feel there is a better way of doing it. I'm thinking something like x:= or window:=, etc.
I'm not sure how to properly define these "named tuple fields" nor how to reference them in subsequent commands?
I'd like to read more on the whole subject if there is a reference link handy.
It seems it would be a better option to use a dictionary here. Dictionaries allow you to set a key, and a value associated to that key. This way you can call a key such as dictionary['x'] and get the corresponding value from the dictionary (if it exists!)
data = ['x:2403 y:368 screen:0 window:60817757'] #Your return data seems to be stored as a list
result = dict(d.split(':') for d in data[0].split())
result['x']
#'2403'
result['window']
#'60817757'
You can read more on a few things here such as;
Comprehensions
Dictionaries
Happy learning!
try
dict(mouse.split(':') for el in mouse
This should give you a dict (rather than tuples, though dicts are mutable and also required hashability of keys)
{x: 2403, y:368, ...}
Also the splitlines is probably not needed, as you are only reading one line. You could do something like:
mouse = [os.popen( "xdotool getmouselocation" ).read()]
Though I don't know what xdotool getmouselocation does or if it could ever return multiple lines.
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.
I am a noob to Python.
I constantly find myself looking at a piece of code and trying to work out what is inside a data structure such as for example a dictionary. In fact the first thing I am trying to work out is "what sort of data structure is this?" and THEN I try to work out how to see what is inside it. I look at a variable and say "is this a dict, or a list, or a multidict or something else I'm not yet familiar with?". Then, "What's inside it?". It's consuming vast amounts of time and I just don't know if I'm taking the right approach.
So, the question is, "How do the Python masters find out what sort of data structure something is, and what techniques do they use to see what is inside those data structures?"
I hope the question is not too general but I'm spending ridiculous amounts of time just trying to fix issues with recognizing data structures and viewing their contents, let alone getting useful code written.
thanks heaps.
Using type() function for the variable will tell you the data type. For example:
inventory = {'cows': 4, 'pigs': 3, 'chickens': 5, 'bears': 2}
print(type(inventory))
will print
<class 'dict'>
which means the variable inventory is a dictionary.
Other possible data types are 'str' for string, 'int' for integer, 'float' for float,'tuple' for tuple, and 'bool' for boolean values.
To see what's inside a collection, you can simply use print() function.
aList = [ 'hunger', 'anger', 'burger']
print(aList)
will output
['hunger', 'anger', 'burger']
I usually care more about how a type is /used/ than what exactly a type is.
For example, if an object is used with say:
foo["hey"] = "there"
for key, value in foo.items():
print key, '->', value
Then I assume that 'foo' is some kind of dict-like object, and unless I have reason to investigate further, that's all I care about.
(Note: I'm still in python 2.x land, the syntax is slightly different in python 3.x, however the point remains)
In stead of "what is this?", with Python it can be better to ask "what does this do?" or "how is this used?". If you see something indexed, such as a['foo'], it shouldn't matter whether it is a dictionary or some other object, but simply that it is indexable by a string.
This idea is usually referred to as Duck Typing, so searching for this might give you some useful info. A quick search turned up this article, which seems relevant for you:
http://www.voidspace.org.uk/python/articles/duck_typing.shtml
I put an import pdb;pdb.set_trace() in the relevant place, and once in the debugger I use dir(), .__dict__ and pp, or any other forms of inspection necessary.
I have a Dictionary of Classes where the classes hold attributes that are lists of strings.
I made this function to find out the max number of items are in one of those lists for a particular person.
def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable
max_vars=0
for key, value in patients[some_person].__dict__.items():
challenger=len(value)
if max_vars < challenger:
max_vars= challenger
return max_vars
What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help!
Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like
for key in patients[some_person].__dict__:
value = patients[some_person].__dict__[key]
# then continue as before
I think a bigger issue, though, will be the fact that dbm only stores strings. So you won't be able to store the list directly in the database; you'll have to store a string representation of it. And that means that when you try to compute the length of the list, it won't be as simple as len(value); you'll have to develop some code to figure out the length of the list based on whatever string representation you use. It could just be as simple as len(the_string.split(',')), just be aware that you have to do it.
By the way, your existing function could be rewritten using a generator, like so:
def find_max_var_amt(some_person):
return max(len(value) for value in patients[some_person].__dict__.itervalues())
and if you did it that way, the change to iterating over keys would look like
def find_max_var_amt(some_person):
dct = patients[some_person].__dict__
return max(len(dct[key]) for key in dct)