I'm trying to set data from database MongoDB for drawing Google Chart in python.
import pymongo
from pymongo import MongoClient
import pandas as pd
from string import Template
import pprint
cluster = MongoClient("mongodb+srv://saman:1234#cluster0-vhwfp.mongodb.net/test?retryWrites=true&w=majority")
db= cluster["Test"]
collection= db["Test"]
rm=list(collection.find({}))
chart_data_str= ''
results= collection.find({})
for x in results:
chart_data_str += '%s,\n' %x
print(chart_data_str)
I want to know, How can I change the folowing format
{'_id': 5, 'name': 'Mahdi', 'Score': 9},
{'_id': 1, 'name': 'Ali', 'Score': 3},
{'_id': 3, 'name': 'Christian', 'Score': 6},
{'_id': 4, 'name': 'Niklas', 'Score': 1},
{'_id': 2, 'name': 'Dominik', 'Score': 2},
{'_id': 0, 'name': 'Saman', 'Score': 5},
to thises format
['Mahdi', 9],
['Ali', 3],
['Christian', 6],
['Niklas', 1],
['Dominik', 2],
['Saman', 5]
thanks
If you just want to print that out as a string:
for result in collection.find({}, {'_id': 0}):
print(f"[{result.get('name')}, {result.get('Score')}],")
If this isn't what you want, please clarify your question.
Related
I have a problem, I have a list like this:
[{'id': 34, 'questionid': 5, 'text': 'yes', 'score': 1}, {'id': 10, 'questionid': 5,
'text': 'test answer updated', 'score': 2}, {'id': 20, 'questionid': 5, 'text': 'no',
'score': 0}, {'id': 35, 'questionid': 5, 'text': 'yes', 'score': 1}]
and I want remove duplicate "questionid", "text" and "score", for example in this case I want output like this:
[{'id': 34, 'questionid': 5, 'text': 'yes', 'score': 1}, {'id': 10, 'questionid': 5,
'text': 'test answer updated', 'score': 2}, {'id': 20, 'questionid': 5, 'text': 'no',
'score': 0}]
How can I get this output in python?
We could create dictionary that has "questionid", "text" and "score" tuple as key and dicts as values and use this dictionary to check for duplicate values in data:
from operator import itemgetter
out = {}
for d in data:
key = itemgetter("questionid", "text", "score")(d)
if key not in out:
out[key] = d
out = list(out.values())
Output:
[{'id': 34, 'questionid': 5, 'text': 'yes', 'score': 1},
{'id': 10, 'questionid': 5, 'text': 'test answer updated', 'score': 2},
{'id': 20, 'questionid': 5, 'text': 'no', 'score': 0}]
I'm using Django 3x. I have one table called Book. When I write a query for this I'm getting data like this:
book_details = Book.objects.all().values()
print(book_details)
<QuerySet [{'id': 1, 'author': 'ABC', 'price': 150, 'category': 'Comic', 'available': 1}, {'id': 2, 'author': 'XYZ', 'price': 500, 'category': 'Historical Fiction', 'available': 1}, {'id': 3, 'author': 'MNO', 'price': 200, 'category': 'Horror', 'available': 0}]>
I'm trying to create data in this below format
{'id':[1,2,3], 'author':['ABC', 'XYZ', 'MNO'], 'price':[150,500,200], 'category':['Comic', 'Historical Fiction', 'Horror'], 'available':[1,1,0]}
How to create data in this format.
Please advise the best way to do this. An explanation would be much appreciated. Thanks!.
If you do:
lst_of_dicts = list(book_details)
You will obtain the following, so if you print lst_of_dicts it will look like this:
[{'id': 1, 'author': 'ABC', 'price': 150, 'category': 'Comic', 'available': 1},
{'id': 2, 'author': 'XYZ', 'price': 500, 'category': 'Historical Fiction', 'available': 1},
{'id': 3, 'author': 'MNO', 'price': 200, 'category': 'Horror', 'available': 0}]
So this is a list of dictionaries, while you want a dict of lists so there is a further step that you must need to do and that is this one:
from itertools import chain # Necessary import
keys = set(chain(*[dic.keys() for dic in lst_of_dicts ]))
final_dict = {key : [dic[key] for dic in lst_of_dicts if key in dic] for key in keys }
final_dict will look like this:
{'id': [1, 2, 3], 'author': ['ABC', 'XYZ', 'MNO'], 'available': [1, 1, 0], 'price': [150, 500, 200], 'category': ['Comic', 'Historical Fiction', 'Horror']}
If given two list of dictionaries (score_list and update_list) below, how do I update score_list from the list of dictionaries from update_list?
score_list = [{'id': 1, 'score': 123}, {'id': 2, 'score': 234}, {'id': 3, 'score': 345}]
update_list = [{'id': 1, 'score': 500}, {'id': 3, 'score': 300}]
# return this
score_list = [{'id': 1, 'score': 500}, {'id': 2, 'score': 234}, {'id': 3, 'score': 300}]
I highly recommend using a mapping when you have a unique key to match:
update_mapping = {d['id']: d for d in update_list}
score_list = [update_mapping.get(d['id'], d) for d in score_list]
I have a json object that I made using networkx:
json_data = json_graph.node_link_data(network_object)
It is structured like this (mini version of my output):
>>> json_data
{'directed': False,
'graph': {'name': 'compose( , )'},
'links': [{'source': 0, 'target': 7, 'weight': 1},
{'source': 0, 'target': 2, 'weight': 1},
{'source': 0, 'target': 12, 'weight': 1},
{'source': 0, 'target': 9, 'weight': 1},
{'source': 2, 'target': 18, 'weight': 25},
{'source': 17, 'target': 25, 'weight': 1},
{'source': 29, 'target': 18, 'weight': 1},
{'source': 30, 'target': 18, 'weight': 1}],
'multigraph': False,
'nodes': [{'bipartite': 1, 'id': 'Icarus', 'node_type': 'Journal'},
{'bipartite': 1,
'id': 'A Giant Step: from Milli- to Micro-arcsecond Astrometry',
'node_type': 'Journal'},
{'bipartite': 1,
'id': 'The Astrophysical Journal Supplement Series',
'node_type': 'Journal'},
{'bipartite': 1,
'id': 'Astronomy and Astrophysics Supplement Series',
'node_type': 'Journal'},
{'bipartite': 1, 'id': 'Astronomy and Astrophysics', 'node_type': 'Journal'},
{'bipartite': 1,
'id': 'Astronomy and Astrophysics Review',
'node_type': 'Journal'}]}
What I want to do is add the following elements to each of the nodes so I can use this data as an input for sigma.js:
"x": 0,
"y": 0,
"size": 3
"centrality": 0
I can't seem to find an efficient way to do this though using add_node(). Is there some obvious way to add this that I'm missing?
While you have your data as a networkx graph, you could use the set_node_attributes method to add the attributes (e.g. stored in a python dictionary) to all the nodes in the graph.
In my example the new attributes are stored in the dictionary attr:
import networkx as nx
from networkx.readwrite import json_graph
# example graph
G = nx.Graph()
G.add_nodes_from(["a", "b", "c", "d"])
# your data
#G = json_graph.node_link_graph(json_data)
# dictionary of new attributes
attr = {"x": 0,
"y": 0,
"size": 3,
"centrality": 0}
for name, value in attr.items():
nx.set_node_attributes(G, name, value)
# check new node attributes
print(G.nodes(data=True))
You can then export the new graph in JSON with node_link_data.
I have a problem try to use $elemMatch in dual nested array:
Suppose I have this a document:
a = {'cart': [[{'id': 1, 'count': 1}, {'id': 2, 'count': 3}], [{'id': 1, 'count': 5}]]}
And I want to select a document out when id is 1 and count greater than 2:
db.cart.find_one({'cart.0.id': 1, 'cart.0.count': {'$gt': 2}})
But this query will select a out.
Then I have tried these queries:
db.cart.find_one({'cart': {'$elemMatch': {'id': 1, 'count': {'$gt': 2}}}})
db.cart.find_one({'cart': {'$elemMatch': {'id': 2, 'count': {'$gt': 2}}}})
db.cart.find_one({'cart.0': {'$elemMatch': {'id': 1, 'count': {'$gt': 2}}}})
db.cart.find_one({'cart.0': {'$elemMatch': {'id': 2, 'count': {'$gt': 2}}}})
But all return None.
So do $elemMatch support the nested array match? If so, how shall I tune my query?
Given the fact that you have an array within an array, I think you could try something like
db.cart.find_one({'cart': {'$elemMatch': { '$elemMatch' : {'id': 1, 'count': {'$gt': 2}}}}})