I have multiple empty lists and dict in side list. I need to extract dict key values in list.
Example:
l =([{'COUNTRY': 'UK', 'STUDENT': 'JOHN'}, {'COUNTRY': 'PT', 'STUDENT':'PEDRO'}, {'COUNTRY': 'UK', 'STUDENT': 'KYLE'}, {'COUNTRY': 'IT', 'STUDENT':'PIRLO'}, {'COUNTRY': 'PT', 'STUDENT':'ANA'}, {'COUNTRY': 'FR', 'STUDENT':'VITO'}, {'COUNTRY': 'FR', 'STUDENT':'LOUIS'}, [], []])
expected result:
k = ['UK', 'PT', 'UK', 'IT', 'PT', 'FR', 'FR']
Related
I need to compare two lists of dictionaries and retrieve the absence elements, "connection" is the attribute who identify the object. The other properties may vary in time. I tried with filters and map but I'm still stuck.
input should look like this:
list1 = [{'username': 'user1', 'connection': "0x2083588'", 'remote': '10.0.5.251:44840','uri': 'www.google.com:443','seconds': '600'}
,{'username': 'user2', 'connection': "0x2a90d778'", 'remote': '10.0.5.251:44796','uri': 'mobilenetworkscoring-pa.googleapis.com:443','seconds': '600'}]
list2 = [{'username': 'user1', 'connection': "0x2083588'", 'remote': '10.0.5.251:44840','uri': 'www.google.com:443','seconds': '400'}
,{'username': 'user2', 'connection': "0x2a90d778'", 'remote': '10.0.5.251:44796','uri': 'mobilenetworkscoring-pa.googleapis.com:443','seconds': '400'}
,{'username': 'user3', 'connection': "0x2a90d678'", 'remote': '10.0.5.251:44796','uri': 'mobilenetworkscoring-pa.googleapis.com:443','seconds': '400'}]
the output should be like this:
[{'username': 'user3', 'connection': "0x2a90d678'", 'remote': '10.0.5.251:44796','uri': 'mobilenetworkscoring-pa.googleapis.com:443','seconds': '400'}]
# Mapping the list1 by "connection" property
mapList = map(lambda y: y.get('connection'), list1)
# Filtering the elements of the second list (list2)
# that are missing from the map of the list1 (mapList) by "connection" property
filterList = filter(lambda x: x.get('connection') not in mapList,list2)
print filterList
I am retrieving data from multiple tables in Django.
my current response is :
{
"status": 0,
"message": "Client details retrived successfully...!!!",
"results": [
{
"id": 11,
"client_id": "CL15657917080578748000",
"client_name": "Pruthvi Katkar",
"client_pan_no": "RGBB004A11",
"client_adhar_no": "12312312313",
"legal_entity_name": "ABC",
"credit_period": "6 months",
"client_tin_no": 4564565,
"client_email_id": "abc#gmail.com",
"head_office_name": "ABC",
"office_name": "asd234",
"office_email_id": "zxc#gmail.com",
"office_contact": "022-27547119",
"gst_number": "CGST786876876",
"office_country": "India",
"office_state": "gujrat",
"office_district": "vadodara",
"office_taluka": "kachh",
"office_city": "vadodara",
"office_street": "New rode 21",
"office_pincode": 2344445,
"contact_person_name": "prasad",
"contact_person_designation": "DM",
"contact_person_number": "456754655",
"contact_person_email": "asd#gmail.com",
"contact_person_mobile": "5675545654",
"created_at": "2019-08-14T14:08:28.057Z",
"created_by": "Prathamseh",
"updated_at": "2019-08-14T14:08:28.057Z",
"updated_by": "prasad",
"is_deleted": false
},
{
"id": 11,
"user_id": "CL15657917080578748000",
"bank_details_id": "BL15657917080778611000",
"bank_name": "Pruthvi",
"branch": "vashi",
"ifsc_code": "BOI786988",
"account_number": 56756765765765,
"account_name": "Pruthvi",
"is_deleted": false
},
{
"id": 10,
"document_details_id": "DL15657917080808598000",
"user_id": "CL15657917080578748000",
"document_type": "Pruthvi ID",
"document": "www.sendgrid.com/pan",
"is_deleted": false
}
]
}
Expected Response :
I am getting the queryset form db in models.py and i am sending it to the views.py and i am iterating over the dict but not getting the expected response.
views.py
#csrf_exempt
def get_client_details(request):
try:
# Initialising lists for storing results
result = []
temp_array = []
# Getting data from request body
client_master_dict = json.loads(request.body)
# Response from get client data
records = ClientDetails.get_client_data(client_master_dict)
# Create response object
# Iterating over the records object for getting data
for i in range(len(records)):
# Converting the querysets objects to json array format
record_result_list = list(records[i].values())
# If multiple records are present
if(len(record_result_list) > 1):
for j in range(len(record_result_list)):
user_info = record_result_list[j]
temp_array.append(user_info)
result.append(temp_array)
temp_array=[]
# For single record
else:
result.append(record_result_list[0])
# Success
returnObject = {
"status" : messages.SUCCESS,
"message" : messages.CLIENT_RETRIVE_SUCCESS,
"results" : result
}
return JsonResponse(returnObject,safe=False)
I think the issue might be in my inner for loop, can anyone help me out with this, is there any way to iterate over the nested JSON object.
Models.py
#classmethod
def get_client_data(cls, client_master_dict):
try:
response_list = []
client_id = client_master_dict['client_id']
client_details = cls.objects.filter(client_id = client_id,is_deleted = False)
bank_details = BankDetails.objects.filter(user_id = client_id,is_deleted = False)
document_details = DocumentDetails.objects.filter(user_id = client_id,is_deleted = False)
response_list.append(client_details)
response_list.append(bank_details)
response_list.append(document_details)
return response_list
except(Exception) as error:
print("Error in get_client_data",error)
return False
Here i'm fetching data from 3 tables and adding it into list.
After printing the data on console i am getting :
[{'id': 11, 'client_id': 'CL15657917080578748000', 'client_name': 'Pruthvi Katkar', 'client_pan_no': 'RGBB004A11', 'client_adhar_no': '12312312313', 'legal_entity_name': 'ABC', 'credit_period': '6 months', 'client_tin_no': 4564565, 'client_email_id': 'abc#gmail.com', 'head_office_name': 'ABC', 'office_name': 'asd234', 'office_email_id': 'zxc#gmail.com', 'office_contact': '022-27547119', 'gst_number': 'CGST786876876', 'office_country': 'India', 'office_state': 'gujrat', 'office_district': 'vadodara', 'office_taluka': 'kachh', 'office_city': 'vadodara', 'office_street': 'New rode 21', 'office_pincode': 2344445, 'contact_person_name': 'prasad', 'contact_person_designation': 'DM', 'contact_person_number': '456754655', 'contact_person_email': 'asd#gmail.com', 'contact_person_mobile': '5675545654', 'created_at': datetime.datetime(2019, 8, 14, 14, 8, 28, 57874, tzinfo=<UTC>), 'created_by': 'Prathamseh', 'updated_at': datetime.datetime(2019, 8, 14, 14, 8, 28, 57874, tzinfo=<UTC>), 'updated_by': 'prasad', 'is_deleted': False}]
[{'id': 11, 'user_id': 'CL15657917080578748000', 'bank_details_id': 'BL15657917080778611000', 'bank_name': 'Pruthvi', 'branch': 'vashi', 'ifsc_code': 'BOI786988', 'account_number': 56756765765765, 'account_name': 'Pruthvi', 'is_deleted': False}]
[{'id': 10, 'document_details_id': 'DL15657917080808598000', 'user_id': 'CL15657917080578748000', 'document_type': 'Pruthvi ID', 'document': 'www.sendgrid.com/pan', 'is_deleted': False}]
Did you check the output of record_result_list? You can outright tell their if it's recovering the data in the format you requested. Try the printing to screen method to debug.
As far as I cam see, the expected output and the hierarchy of results for bank details are not matching. I don't know how you are handling the hierarchy. Are you directly taking it from JSON as the hierarchy? Or are you just taking the data and creating hierarchy in the expected output?
I have a list as following:
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
My code is as following
import re
[item2 for item in list12 for item2 in item.split() if not re.match("^[*A-Z]+(0-9){4}$", item2)]
I got output like :
['First', 'Company', 'limited', 'Apple', 'Technology', 'Sami']
I expect the output to be like :
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
I am not good with regular expression. How can I reach to my required solution?
A non-regex way in python,
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
str = " ".join(list12)
list21 = str.split()
res = [k.strip('*') for k in list21 if '**' not in k]
print(res)
Output:
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
DEMO: http://tpcg.io/s9aBhe
Seems you're looking for
\b([A-Za-z]+)\b
In Python:
import re
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
rx = re.compile(r'\b([A-Za-z]+)\b')
result = [word for item in list12 for word in rx.findall(item)]
print(result)
Which yields
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
Is there any nice pythonic way of merging dictionaries within a list?
What I have:
[
{ 'name': "Jack" },
{ 'age': "28" }
]
What I would like:
[
{ 'name': "Jack", 'age': "28" }
]
Here's a method that uses dict.update(). In my opinion it's a very readable solution:
data = [{'name': 'Jack'}, {'age': '28'}]
new_dict = {}
for d in data:
new_dict.update(d)
new_data = [new_dict]
print new_data
OUTPUT
[{'age': '28', 'name': 'Jack'}]
If you're using Python 3, you can use collections.ChainMap:
>>> from collections import ChainMap
>>> ld = [
... { 'name': "Jack" },
... { 'age': "28" }
... ]
>>> [dict(ChainMap(*ld))]
[{'name': 'Jack', 'age': '28'}]
You could use list comprehension:
final_list = [{key: one_dict[key]
for one_dict in initial_list
for key in one_dict.keys()}]
Edit: the list comprehension was backwards
out = reduce(lambda one, two: dict(one.items() + two.items()),
[{'name': 'Jack'}, {'age': '28'}, {'last_name': 'Daniels'}])
print(out)
OUTPUT
{'age': '28', 'last_name': 'Daniels', 'name': 'Jack'}
I have a list:
txtlst = [
['000001', 'DOE', 'JOHN', 'COMSCI', '', 'MATH', '', 'ENGLISH\n'],
['000002', 'DOE', 'JANE', 'FRENCH', '', 'MUSIC', '', 'COMSCI\n']
]
And I want to put the elements in a dictionary so it looks likes this
mydict = {
'000001': ['000001', 'DOE', 'JOHN', 'COMSCI', '', 'MATH', '', 'ENGLISH\n'],
'000002': ['000002', 'DOE', 'JANE', 'FRENCH', '', 'MUSIC', '', 'COMSCI\n']
}
My problem here is, after I ran the code
for i in txtlst:
key = i[0]
value = i
mydict = {key:value}
The two sublists of txtlst are added to different dictionaries. How can I fix my code so they will be in the same dictionary as I mentioned above?
You can easily create a new dictionary with the first element of each list as key:
mydict = { i[0]: i for i in txtlst }
If you wish to do that in a loop like in your approach, you need to initialize a dictionary beforehand and update it in each iteration:
mydict = {}
for i in txtlst:
key = i[0]
value = i
mydict[key] = value