Get similar named keys from dictionary? [duplicate] - python

This question already has answers here:
Slicing a dictionary by keys that start with a certain string
(3 answers)
Closed 2 years ago.
I have a dictionary like this:
'id': 6, 'user_id': 1, 'approved': 0, 'is_ok': 0, 'solution': '2', 'category': '2', 'language': '2', 'hint_1': '1', 'hint_2': '2', 'hint_3': '3', 'hint_4': '4', 'hint_5': '5', 'hint_6': '6', 'hint_7': '7', 'hint_8': '8', 'hint_9': '9', 'hint_10': '2', 'hint_11': '2', 'hint_12': '2', 'hint_13': '2', 'hint_14': '2', 'hint_15': '2', 'hint_16': '2', 'hint_17': '2', 'hint_18': '2', 'hint_19': '2', 'hint_20': '2'
Is there a way to get a list of all values, where the key starts with hint_?, ? being placeholder?
Thanks.
I think it could be done via a function that compares strings, but there might be a better solution!?

Handy one-liner:
[item for key, item in dictionary.items() if key.startswith('hint_')]

Related

How do I stop Python treating list items as one item instead of multiple when appending to another list? [duplicate]

This question already has answers here:
What is the difference between Python's list methods append and extend?
(20 answers)
Closed last month.
I have a list called MBN2 thats values are 15 and 13. I'm trying to append it to another list called BoutNumber2, but when I try to do this it treats MBN2 as one list item ['15', '13'] instead of two. When I print the length of MBN2 it says two so I'm not sure why it's doing this. Here is the block of code
for test4 in soup.select('.fight_card_resume'):
MBN2.append(test4.find('td').get_text().replace('Match ', ''))
for test7 in soup.select('.new_table_holder [itemprop="subEvent"] td'):
BoutNumber.append(test7.get_text().strip())
BoutNumber2 = BoutNumber[0::7]
BoutNumber2.append(MBN2)
and this is what I get when I print BoutNumber2 afterwards
['14', '13', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', ['15', '13']]
How do I get Python to treat the appended 15 and 13 as seperate?
Just this should work:
BoutNumber2 = BoutNumber2 + MBN2
or you could do
BoutNumber2.extend(MBN2)
Both solutions should do the job.

turning a string representation of a nested list inside a list into a list [duplicate]

This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Apply function to each element of a list
(4 answers)
Closed 6 months ago.
I need to turn
x = ["['born', '0', '15']", "['in', '2', '15']", "['a', '2', '15']", "['world', '3', '00']"]
into
x = [['born', '0', '15'], ['in', '2', '15'], ['a', '2', '15'], ['world', '3', '00']]
as it coded so that the first value of the nested list would be used as a name, the second value would be length in hours and third value is length in minutes.
This is about how to convert string to list
You can try something as below
y = []
for i in x:
y.append(eval(i))
print(y)
output
[['born', '0', '15'], ['in', '2', '15'], ['a', '2', '15'], ['world', '3', '00']]

listing the keys in a dictionary created from mongoengine object

I'm working on a little flask project and I've used mongoengine to get the info from a mongodb document as follows:
results = User.objects.filter(class_name=class_name)
I now want to create a table that will display the data from the results with the keys in the table header and then the data below in rows. I'm having trouble displaying the keys, for example if I do:
for key in results.keys():
print (key)
but I get the error:
AttributeError: 'BaseQuerySet' object has no attribute 'keys'
When I print the results, the terminal shows:
[<User: User object>, <User: User object>]
[<User: User object>, <User: User object>]
[<User: User object>, <User: User object>]
So, I guess it isn't a normal dictionary or something? I'm just learning using python and coding in general so any help would be appreciated for this home project, thanks
As a first step, you could ...
print(type(myresults))
... so you learn what type of object is returned.
You can also e.g. print(dir(myresults)), so you will get a list of attributes and methods of this object.
Found a solution, in the BaseQueryList there is one method called as_pymongo, it can be used to get rows as list of dict like where we get pymongo:
results = User.objects.filter(class_name=class_name).as_pymongo
so now when I print the results, it prints as a dictionary list:
{'_id': ObjectId('5f01925804723f383c2dd483'), 'user_id': '2', 'first_name': 'Alan', 'last_name': 'Rice', 'username': 'arice', 'password': 'xxxxxxxx', 'class_name': '6a', 'E6001': '2', 'E6002': '2', 'E6003': '2', 'E6004': '9', 'E6005': '2', 'E6006': '2', 'E6007': '9', 'E6008': '2', 'E6009': '2', 'E6010': '2', 'E7001': '7', 'E7002': '2', 'E7003': '2', 'E7004': '7', 'E7005': '2', 'E7006': '2', 'E7007': '2', 'E7008': '2', 'E7009': '2', 'E7010': '2', 'M6001': '2', 'M6002': '2', 'M6003': '2', 'M6004': '2', 'M6005': '2', 'M6006': '2', 'M6007': '2', 'M6008': '2', 'M6009': '2', 'M6010': '2', 'M7001': '2', 'M7002': '2', 'M7003': '2', 'M7004': '2', 'M7005': '2', 'M7006': '2', 'M7007': '2', 'M7008': '2', 'M7009': '2', 'M7010': '2'}

How to sort a list of integers that are stored as string in python [duplicate]

This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 2 years ago.
I tried to sort a list of string that are actually integers but i do not get the right sort value. How do i sort it in a way that it is sorted according to the integer value of string ?
a = ['10', '1', '3', '2', '5', '4']
print(sorted(a))
Output:
['1', '10', '2', '3', '4', '5']
Output wanted:
['1', '2', '3', '4', '5', '10']
We have to use the lambda as a key and make each string to int before the sorted function happens.
sorted(a,key=lambda i: int(i))
Output :
['1', '2', '3', '4', '5', '10']
More shorter way -> sorted(a,key=int). Thanks to #Mark for commenting.
So one of the ways to approach this problem is converting the list to a list integers by iterating through each element and converting them to integers and later sort it and again converting it to a list of strings again.
You could convert the strings to integers, sort them, and then convert back to strings. Example using list comprehensions:
sorted_a = [str(x) for x in sorted(int(y) for y in a)]
More verbose version:
int_a = [int(x) for x in a] # Convert all elements of a to ints
sorted_int_a = sorted(int_a) # Sort the int list
sorted_str_a = [str(x) for x in sorted_int_a] # Convert all elements of int list to str
print(sorted_str_a)
Note: #tedd's solution to this problem is the preferred solution to this problem, I would definitely recommend that over this.
Whenever you have a list of elements and you want to sort using some property of the elements, use key argument (see the docs).
Here's what it looks like:
>>> a = ['10', '1', '3', '2', '5', '4']
>>> print(sorted(a))
['1', '10', '2', '3', '4', '5']
>>> print(sorted(a, key=lambda el: int(el)))
['1', '2', '3', '4', '5', '10']

Getting "keys" from list of dicts [duplicate]

This question already has answers here:
How to return dictionary keys as a list in Python?
(13 answers)
Closed 4 years ago.
I have the following data:
[{'id': ['132605', '132750', '132772', '132773', '133065', '133150', '133185', '133188', '133271', '133298']},
{'number': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']},
{'id': ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']}]
What would be the best way to get a list of the keys (as if it was a dict and not an array)? Currently I'm doing:
>>> [list(i.keys())[0] for i in e.original_column_data]
['id', 'number', 'id']
But that feels a bit hackish
What is hacky about it? It's a bit inelegant. You just need to do the following:
>>> keys = []
>>> data = [{'id': ['132605', '132750', '132772', '132773', '133065', '133150', '133185', '133188', '133271', '133298']},
... {'number': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']},
... {'id': ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']}]
>>> for d in data:
... keys.extend(d)
...
>>> keys
['id', 'number', 'id']
Or if you prefer one-liners:
>>> [k for d in data for k in d]
['id', 'number', 'id']
first way
iteration on a dictionary gives you its keys, so a simple
>>> [key for key in dict]
gives you a list of keys and you can get what you want with
>>> [key for dict in dict_list for key in dict]
second way (only python 2)
use .key() (used in your code)
but there is no need to use list() (edit: for python 2)
here's what it will look like:
>>> [dict.keys()[0] for dict in dict_list]
in your code, dictionaries have only one key so these two have the same result.
but I prefer the first one since it gives all keys of all the dictionaries
This is simpler and does the same thing:
[k for d in e.original_column_data for k in d]
=> ['id', 'number', 'id']

Categories