Here is my code:
def getDownloaders(dbPATH):
with sqlite3.connect(dbPATH) as db:
cursor = db.cursor()
cursor.execute("SELECT * FROM Downloaders")
d = cursor.fetchall()
downloader = {}
column_names = [s[0] for s in cursor.description]
for i in range(len(d)):
for row in d:
downloader[i] = dict(zip(column_names, row))
print(downloader)
return downloader
Here is my data:
[{1, 'lll', ‘lll', 'lll', '', ‘1’, 'lobio', 'c:/'},
{2, 'test', ‘test3', 'blob', 'blah', ‘1’, 'lio', 'c:/'},
{3, 'ledere', ‘copsssss', 'reds', 'server', ‘0’, 'lobio', 'c:/'}]
Here is what I want in a dictionary
{0: {'id': 1, 'Host': 'lll', 'username': 'lll', 'password': 'lll', 'label': 'lll', 'Enabled': 1, 'name': 'lobio', 'file': 'c:/'}, 1: {'id': 2,'Host': 'test', 'username': 'test3', 'password': 'blob', 'label': 'blah', 'Enabled': 1, 'name': 'lio', 'file': 'c:/'}, 2: {'id': 3, 'Host': 'lwderel', 'username': ‘copsssss', 'password': 'reds', 'label': 'server', 'Enabled': 0, 'name': 'lobio', 'file': 'c:/'}}
You have two nested for loops, for all row indexes, and for all rows, so the innermost line sees all combinations of i and row (3×3), even those where these two do not match.
You have to use a single loop:
cursor.execute("...")
column_names = [s[0] for s in cursor.description]
downloader = {}
i = 0
for row in cursor:
downloader[i] = dict(zip(column_names, row))
i += 1
And a dictionary with consecutive numbers as keys is pointless; it would be simpler to use an array as return value:
cursor.execute("...")
column_names = [s[0] for s in cursor.description]
downloader = [dict(zip(column_names, row)) for row in cursor]
Related
I want to remove duplicates dictionaries from list of dictionaries. I am trying to make configurable code to work on any field instead of making field specific.
Input Data
dct = {'Customer_Number': 90617174,
'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280.0]},
{'Phone_Type': 'Mobile', 'Phone': [12177218280.0]}],
'Email': [{'Email_Type': 'Primary',
'Email': ['saman.zonouz#rutgers.edu']},
{'Email_Type': 'Primary',
'Email': ['saman.zonouz#rutgers.edu']}]
}
Expected Output:
{'Customer_Number': 90617174,
'Email': [{'Email_Type': 'Primary',
'Email': ['saman.zonouz#rutgers.edu']}],
'Phone_Number': [{'Phone_Type': 'Mobile',
'Phone': [12177218280]}]}
**Code tried:**
res_list = []
for key,value in address_dic.items():
if isinstance(value,list):
for i in range(len(value)):
if value[i] not in value[i + 1:]:
res_list.append(value[i])
dic.append((res_list))
**Output Getting**
type: [[{'Email_Type': 'Primary', 'Email': ['saman.zonouz#rutgers.edu']}, {'Email_Type': 'alternate', 'Email': ['samance#gmail.com', 'saman.zonouz#rutgers.edu']}], [], [{'Phone_Type': 'Mobile', 'Phone': [12177218280.0]}, {'Phone_Type': 'work', 'Phone': [nan]}, {'Phone_Type': 'home', 'Phone': [2177218280.0]}], []]
Write a function to dedupe lists:
def dedupe_list(lst):
result = []
for el in lst:
if el not in result:
result.append(el)
return result
def dedupe_dict_values(dct):
result = {}
for key in dct:
if type(dct[key]) is list:
result[key] = dedupe_list(dct[key])
else:
result[key] = dct[key]
return result
Test it:
deduped_dict = {'Customer_Number': 90617174,
'Email': [{'Email_Type': 'Primary',
'Email': ['saman.zonouz#rutgers.edu']}],
'Phone_Number': [{'Phone_Type': 'Mobile',
'Phone': [12177218280]}]}
dedupe_dict_values(dct) == deduped_dict
## Out[12]: True
I would like to iterate through a multiple array list within the dictionary. Please suggest.
Provided the code that i have tried.
Below is the dictionary, that i need to iterate through and print key and value.
{
'page': 2,
'per_page': 6,
'total': 12,
'total_pages': 2,
'data': [
{
'id': 7,
'email': 'michael.lawson#reqres.in',
'first_name': 'Michael',
'last_name': 'Lawson',
'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg'
},
{
'id': 8,
'email': 'lindsay.ferguson#reqres.in',
'first_name': 'Lindsay',
'last_name': 'Ferguson',
'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg'
},
{
'id': 9,
'email': 'tobias.funke#reqres.in',
'first_name': 'Tobias',
'last_name': 'Funke',
'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg'
},
{
'id': 10,
'email': 'byron.fields#reqres.in',
'first_name': 'Byron',
'last_name': 'Fields',
'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg'
},
{
'id': 11,
'email': 'george.edwards#reqres.in',
'first_name': 'George',
'last_name': 'Edwards',
'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg'
},
{
'id': 12,
'email': 'rachel.howell#reqres.in', 4
'first_name': 'Rachel',
'last_name': 'Howell',
'avatar': 'https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg'
}
]
}
My code:
import json
res = requests.get('https://reqres.in/api/users?page=2')
data = res.content
print(type(data))
jsondata = json.loads(data)
print(type(jsondata)) # Turning JSON encoded data into Python objects.
jsondata = json.dumps(jsondata, indent=4) # Serialize the json data
print(type(jsondata))
print(jsondata)
res1 = requests.get('https://reqres.in/api/users?page=2')
data1 = res1.content
print(data1)
jsondata1 = json.loads(data1)
jsondata1 = json.dumps(jsondata1)
print(jsondata1)
for key, value in jsondata.items():
print(key, '->', value)
From the dictionary, we need to print all,
Key
Value
import json
import requests
def printseq(seq):
if (isinstance(seq,dict)):
for key,values in seq.items():
if (isinstance(values,list)):
for i in values:
if (isinstance(i,dict)):
printseq(i)
else:
print(key,"->",values)
res=requests.get('https://reqres.in/api/users?page=2')
data=res.content
jsondata = json.loads(data)
printseq(jsondata)
Try this out, here in this code recursive procedure is used to print dictionary.
Before printing value isinstance() method is used to check the type of value and if it is dictionary recursion is called.
I am trying to create a list structure in a loop:
[children:[{text: "Title 1", id: '1', expanded: true,children: [{text: "title2", leaf: true ,},{text: "title3", leaf: true}]},{text: "Title4", id: '4', expanded: true, children: [{text: "title5", leaf: true,} ]}]]
The source data looks like this:
mylist =[{'id': '1', 'name': 'Title1', 'id_parent': '0'}, {'id': '2', 'name': 'title2', 'id_parent': '1'}, {'id': '3', 'name': 'title3', 'id_parent': '1'}, {'id': '4', 'name': 'Title4', 'id_parent': '0'}, {'id': '5', 'name': 'title5', 'id_parent': '4'}]
Using recursion, I go through the data and get parental and childish records:
def get_parent(id_parent):
c = []
for x in mylist:
if not x["id"] == id_parent and x["id_parent"] == id_parent:
if x["id_parent"] == id_parent:
x['expanded'] = True
else:
x['leaf'] = True
c.append(x)
return(c)
def get_tree(t):
lst = []
main_data = []
for x in get_parent(t):
all_stor = {}
all_stor["text"] = x['name']
all_stor["id"] = x['id']
if x.get('expanded'):
all_stor["expanded"] = x['expanded']
else:
all_stor["leaf"] = x['leaf']
main_data.append(all_stor)
lst.append([main_data, get_tree(x["id"])])
return lst
main = get_tree("0")
print(main)
How to fill the main_data list in a loop in order to get the necessary structure?
Your expected output should be a list of children from the root level:
def get_tree(l, parent='0'):
children = []
for d in l:
if d['id_parent'] == parent:
details = {'text': d['name'], 'id': d['id']}
grand_children = get_tree(l, d['id'])
if grand_children:
details.update({'expanded': True, 'children': grand_children})
else:
details['leaf'] = True
children.append(details)
return children
so that with your sample input, get_tree(mylist) would return:
[{'text': 'Title1', 'id': '1', 'expanded': True, 'children': [{'text': 'title2', 'id': '2', 'leaf': True}, {'text': 'title3', 'id': '3', 'leaf': True}]}, {'text': 'Title4', 'id': '4', 'expanded': True, 'children': [{'text': 'title5', 'id': '5', 'leaf': True}]}
I want to sort by uid
rsp=[
{'user': {'uid': 1, 'name': 'Bob'}},
{'user': {'uid': 5, 'name': 'Sid'}},
{'user': {'uid': 2, 'name': 'Cas'}},
]
to
rsp=[
{'user': {'uid': 1, 'name': 'Bob'}},
{'user': {'uid': 2, 'name': 'Cas'}},
{'user': {'uid': 5, 'name': 'Sid'}},
]
Ive tried this way.....but it doesn't work
result = sorted(rsp, key=itemgetter('user').itemgetter('uid'))
You can pass a lambda function to the key argument:
result = sorted(rsp, key=lambda x: x.get('user', {}).get('uid', -1) )
In this case I am using get to ensure the sort does not fail if one of the elements does not have a user key, and any sub-dictionaries that do not have a uid key will be place first.
You can try this as your key to sort your list of dictionaries:
rsp.sort(key = lambda x: x['user']['uid'])
>>> rsp
[{'user': {'uid': 1, 'name': 'Bob'}}, {'user': {'uid': 2, 'name': 'Cas'}}, {'user': {'uid': 5, 'name': 'Sid'}}]
group1= [ {
'Name': 'C21114',
'Description': '',
'num': '12321114',
'working': 'true',
'belongs': 'Default',
'Expiry_Date': '',
'\xef\xbb\xbfUser_ID': 'C21114',
'Password': '*SECRET*',
},
{
'Name': 'Mahes',
'Description': '',
'num': '1026',
'working': 'true',
'belongs': 'Default',
'Expiry_Date': '',
'\xef\xbb\xbfUser_ID': 'Mahi',
'Password': '*SECRET*',
},
{
'Name': 'pri',
'Description': '',
'num': '1027',
'working': 'true',
'belongs': 'Default',
'Expiry_Date': '',
'\xef\xbb\xbfUser_ID': 'priya',
'Password': '*SECRET*',
}]
group2= [{
'Name': 'C21114',
'Description': '',
'num': '12321114',
'working': 'true',
'belongs': 'Default',
'Expiry_Date': '',
'User_ID': 'C21114',
'Password': '*SECRET*',
},
{
'Name': 'Mahes',
'Description': '',
'num': '1026',
'working': 'true',
'belongs': 'Default',
'Expiry_Date': '',
'User_ID': 'Mahi',
'Password': '*SECRET*',
},
{
'Name': 'pri',
'Description': '',
'num': '1027',
'working': 'true',
'belongs': 'Default',
'Expiry_Date': '',
'User_ID': 'priya',
'Password': '*SECRET*',
}]
Need to compare few keys of group1 and group2 are same or not. group1 and group2 are list in that many dictionaries.I just need to compare few keys with its values between group1 and group2.Explained with one example.Example : keys_to_compare = {'name', 'num',working} from group1 and group2.
This should do what you need it to do
key_to_compare = ['Name', 'num', 'working']
for key in key_to_compare:
for d1 in group1:
for d2 in group2:
if d1[key] == d2[key]:
print "same values for %s %s %s" % (key, d1[key], d2[key])
Change the if statement to do what you would like for elements with the same value.
I had to make an assumption on what the output you wanted. I created a list of lists. The inner most list is a part of indexs (group1 then group2) of matches. This is the code:
keys_to_compare = ['Name','num','working']
matches = []
for idx1 in range(len(group1)):
ref1 = group1[idx1]
found = False
for idx2 in range(len(group2)):
ref2 = group2[idx2]
found = True
for key in keys_to_compare:
if ref1[key] != ref2[key]:
found = False
if found:
matches.append([idx1,idx2])
break
if found: continue
print 'matches=%r' % (matches)
The result:
matches=[[0, 0], [1, 1], [2, 2]]
Implemented as a function, this should give you what you want:
def compare(key):
g1 = []
g2 = []
for i in group1:
g1.append(i[key])
for j in group2:
g2.append(j[key])
return g1 == g2
Put in the key name, then it will return True if the values are same in both groups and False if not. For instance, to check the keys in your list, you'll do:
keys_to_compare = ['Name','num','working']
for x in keys_to_compare:
print compare(x)