listing the keys in a dictionary created from mongoengine object - python

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'}

Related

Replace item of QComboBox - pyside

I have a combobox where i add items in this way
tmp_list = ['1', '2', '3', '4']
tmp_list2 = ['5', '6', '7', '8']
self.combobox = QComboBox()
self.combobox.addItem('First Item', tmp_list)
self.combobox.addItem('Second Item', tmp_list2)
Somewhere in my code tmp_list changes intentionally and I want to update the data.
tmp_list = ['8', '9', '7', '6']
How can i set the new list for First Item without losing Second Item.
I thought about using the .removeItem() function but how do I get the index of the item?
Knowing that there are not only 2 items

Get similar named keys from dictionary? [duplicate]

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_')]

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']

Removing duplicated numbers within tuples

For example I want to remove the extra 1s and 2s in this tuple ( '1',
'1',
'1',
'1',
'1',
'1',
'1',
'2',
'2',
'2') to return ('1', '2')
How can I do this?
You can't modify tuple in place, So definitely you have to get new tuple. You can use set to remove duplicate elements.
>>> tp = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2')
>>> tp = tuple(set(tp))
>>> tp
('1', '2')
As Alok correctly mentions, you have to create a new tuple. As Alok demonstrates, you can of course assign it to the variable that previously held the original tuple.
If you don't care about order, use set as Alok suggests. If you however want to preserve the order (of first occurrence of each unique value), you can use a very similar trick with an OrderedDict:
from collections import OrderedDict
# Different example to demonstrate preserved order
tp = ('2', '2', '2', '1', '1', '1', '1', '1', '1', '1')
tp = tuple(OrderedDict.fromkeys(tp).keys())
# Now, tp == ('2', '1')
They are correct, tuples in python are immutable therefore you cannot update the current tuple. This function loops through data creating a list of indexes that do not currently exist! It then returns a tuple of the list! Good luck!
data = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '3', '4','4')
def removeDoubles(data):
out = []
for i in data:
if i in out:
continue
out.append(i)
del data
return tuple(out)
print removeDoubles(data)
You can do this using a set:
a = ( '1', '1', '1', '1', '1', '1', '1', '2', '2', '2')
b = tuple(set(a))
If the order is important you could sort b.

List circulation in Python for Project Euler 37

So, I was doing Project Euler 37
I need to circulate a list
input: 2345 # converted to list inside function
expected output: [[3,4,5,2],[4,5,2,3],[5,2,3,4],[2,3,4,5]]
Here is my function for that
def circulate(n): #2345
lst=list(str(n)) #[2,3,4,5]
res=[]
for i in range(len(lst)):
temp=lst.pop(0)
lst.append(temp)
print lst #print expected list
res.append(lst) #but doesn't append as expected
return res
print circulate(2345)
My output is:
['3', '4', '5', '2']
['4', '5', '2', '3']
['5', '2', '3', '4']
['2', '3', '4', '5']
[['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5']]
The function prints lst correct every time, but doesn't append as expected.
What I am doing wrong?
You need to append copies of your list to res:
res.append(lst[:])
You were appending a reference to the list being altered instead; all references reflect the changes made to the one object.
You may want to look at collections.deque() instead; this double-ended list object supports efficient rotation with a .rotate() method:
from collections import deque
def circulate(n):
lst = deque(str(n))
res = []
for i in range(len(lst)):
lst.rotate(1)
res.append(list(lst))
return res

Categories