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.
Related
When trying to iterate through a defaultdict my variables were read as strings when they should be read as lists, however, when I changed my code a little bit, it worked but I don't know exactly why. My defaultdict is a dictonary that has a list of dictionaries inside it. The code looked like that
for engagement in engagement_by_account:
for engagement in engagement:
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
And the error was:
TypeError: string indices must be integers
However, when I changed the code to this:
for key,engagement in engagement_by_account.items():
for engagement in engagement:
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
there were no errors anymore.
By default, when you iterate over a dictionary (or defaultdict), you will iterate over the keys of that dictionary. It seems here that you wanted to iterate over the values so you could either do what you did or something like:
for engagements in engagement_by_account.values():
for engagement in engagements:
engagement['total_minutes_visited'] = float(engagement['total_minutes_visited'])
I start by downloading some tweets from Twitter.
tweet_text = DonaldTrump["Tweets"]
tweet_text = tweet_text.str.lower()
Then in next step, we move with TweetTokenizer.
Tweet_tkn = TweetTokenizer()
tokens = [Tweet_tkn.tokenize(t) for t in tweet_text]
tokens[0:3]
Can someone explain to me and help me solve it.
I have been through similar questions that face similar errors but they provide different solutions.
Lists are mutable and can therefore not be used as dict keys. Otherwise, the program could add a list to a dictionary, change its value, and it is now unclear whether the value in the dictionary should be available under the new or the old list value, or neither.
If you want to use structured data as keys, you need to convert them to immutable types first, such as tuple or frozenset. For non-nested objects, you can simply use tuple(obj). For a simple list of lits, you can use this:
tuple(tuple(elem) for elem in obj)
But for an arbitrary structure, you will have to use recursion.
the python program that i am writing calls to an api that returns this json:
Code Output
How do i access the subdetails? When i run the .keys() it only lists those three top levels. I want to be able to get specific items, e.g. "Utility"
I've tried several solutions but none parse correctly. I have tried calling the list inside the dictionary, to no avail. Originally i thought it was a dictionary inside of a dictionary, but Python thinks its a list nested into a dictionary.
Any help would be appreciated!
keys() function only returns the keys of dictionary, so it you call keys(), it will only return the three result. The "subdetails" you are referring to are the values of those keys. For key "SUMMARY" as an example, its value is a list instead of dict (note the "[" after the key). However, the list only has a single element. This is quite common in json. To retrive "Utility", all you need to do is data['SUMMARY'][0]['Utility']
Maybe to help you understand the data structure better, call the "values()" and "items()" function to see what it returns.
Since it's a dict of lists of dicts, simply use an index of 0 to access the first item of the list if there is always only one item in each list. For example, if your JSON object is stored as variable data, then the value of Utility can be accessed with data['SUMMARY'][0]['Utility'].
I'm relatively new to python and programing and have code that is working, however I'd like to know if there is a better more condensed way to achieve the same thing.
My code creates a dictionary with some context key value pairs, then I go and get groups of questions looping a number of times. I want to gather all the questions into my data dictionary, adding the list of questions the first time, and extending it with subsequent loops.
My working code:
data = {
'name': product_name,
'question summary': question_summary,
}
for l in loop:
<my code gets a list of new questions>
if 'questions' not in data:
data ['questions'] = new_questions['questions']
else:
all_questions = data.get('questions')
all_questions.extend(new_questions['questions'])
data ['questions'] = all_questions
I've read about using a default dict to enable automatic creation of a dictionary item if it doesn't exist, however I'm not sure how I would define data in the first place as some of its key value pairs aren't lists and I want it to have the extra context key value pairs.
I also feel that the 3 lines of code appending more questions to the list of questions in data (if it exists) should/could be shorter but this doesn't work as data.get() isn't callable
data['questions'] = data.get('questions').extend(new_questions['questions'])
and this doesn't work because extend returns none:
data['questions'] = all_questions.extend(new_questions['questions'])
Ok so I figured out how to condense the 3 lines, see answer, below however I'd still like to know if the If: else: is good form in this case.
You might be looking for the setdefault method:
data.setdefault('questions', []).extend(new_questions['questions'])
Ok so Quack Quack I figured out how to condense the 3 lines - this works:
data['questions'].extend(new_questions['questions'])
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)