Related
I have two lists in Python something similar.
list1 = [
{"name": "sample1",
"place": "sampleplace1",
"value": "",
"time": "sampletime"
},
{"name": "sample2",
"place": "sampleplace2",
"value": "",
"time": "sampletime2"
}
]
list2 = [
{"name": "sample1",
"value": "10"
},
{"name": "sample2",
"value": "20"
}
]
I need to compare both the lists and whereever the name is matching, I need to update the value property in list1. I did by running a for loop on list1, get the matching list object from list2 for each list1 object and update the value.
I'm just wondering, is there a way to do this without running a for loop (something like Linq in C#)?
Sadly, Python does not have the same abilities as LINQ.
If you don't want to explicitly use a function there is map, but it uses a loop under the hood, as LINQ does.
You need for loops, like in :
list1 = [
{"name": "sample1",
"place": "sampleplace1",
"value": "",
"time": "sampletime"
},
{"name": "sample2",
"place": "sampleplace2",
"value": "",
"time": "sampletime2"
}
]
list2 = [
{"name": "sample1",
"value": "10"
},
{"name": "sample2",
"value": "20"
}
]
for elem1 in list1:
for elem2 in list2:
if elem1["name"] == elem2["name"]:
# match ! we replace the value
elem1["value"] = elem2["value"]
break # and stop searching
else:
print(f"no match in list2 for {elem1['name']=}")
# just for displaying the result
import json
print(json.dumps(list1, indent=2))
[
{
"name": "sample1",
"place": "sampleplace1",
"value": "10",
"time": "sampletime"
},
{
"name": "sample2",
"place": "sampleplace2",
"value": "20",
"time": "sampletime2"
}
]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
list_1 = [
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Owner" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Employ" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Manager" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "100", "name": "last", "email": "last#network.com", "type": "Manager" }
]
list_2 = [
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Employ" },
{ "id": "52", "name": "abcded", "email": "abcded#network.com", "type": "Manager" }
]
A preference dictionary {'Owner': 1, 'Manager':2, 'employ':3, 'HR': 4 }
There are two list of dictionaries
list_1 is the primary_dictionary, list_2 is the secondary_dictionary
I need to update the role in list_1 dictionary if the 'email' present in secondary dictionary with respect to check in preference dictionary
In the end output i should contain 'type' as in preference dictionary
If any emails match I want to update list one at all places with that email to contain a new role under'type'. for example if 123#gmail.com was in a dictionary within list2 then I want to change every item in list1 that contains 123#gmail.com as the email to have a role that is determined by a selection from the preference dictionary.
Expected out
[
{'id': '11', 'name': 'son', 'email': 'n#network.com', 'type': 'Owner'},
{'id': '21', 'name': 'abc', 'email': 'abc#network.com', 'type': 'Manager'},
{"id": "100", "name": "last", "email": "last#network.com", "type": "Manager"}
]
Code is below
for each1 in list_1:
for each2 in list_2:
if each1['email'] == each2['email']:
# Update the list_1 dictionary with respect to preference
Given the following inputs:
list_1 = [
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Owner" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Employ" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Manager" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "100", "name": "last", "email": "last#network.com", "type": "Manager" }
]
list_2 = [
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Employ" },
{ "id": "52", "name": "abcded", "email": "abcded#network.com", "type": "Manager" }
]
preference = {'Owner': 1, 'Manager':2, 'Employ':3, 'HR': 4 }
I would start by reshaping list_2 into something more useable. This will get rid of the duplicates leaving us just the "best" type for each email:
list_2_lookup = {}
for item in list_2:
key, value = item["email"], item["type"]
list_2_lookup.setdefault(key, value)
if preference[value] < preference[list_2_lookup[key]]:
list_2_lookup[key] = value
Then we can iterate over the items in the first list and use the lookup we just created. Note, this is a little more convoluted than might be needed as it is not clear from your question and your expected result what items from list_1 should actually appear in the output. I have tried to match your stated output.
result = {}
for item in list_1:
key = item["email"]
result.setdefault(key, item)
if preference[result[key]["type"]] > preference[item["type"]]:
result[key]["type"] = item["type"]
if preference[result[key]["type"]] > preference.get(list_2_lookup.get(key), 99):
result[key]["type"] = list_2_lookup.get(key)
At this point we can:
print(list(result.values()))
Giving us:
[
{'id': '11', 'name': 'son', 'email': 'n#network.com', 'type': 'Owner'},
{'id': '21', 'name': 'abc', 'email': 'abc#network.com', 'type': 'Manager'},
{'id': '100', 'name': 'last', 'email': 'last#network.com', 'type': 'Manager'}
]
Here is code that will do the following:
If any emails match update list one at all places with that email to contain a new role under 'type'. for example if 123#gmail.com was in a dictionary within list2 then it will change change every item in list1 that contains 123#gmail.com as the email to have a role that is determined by a selection from the preference dictionary.
list_1 = [
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Owner" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Employ" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Manager" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "100", "name": "last", "email": "last#network.com", "type": "Manager" }
]
list_2 = [
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "11", "name": "son", "email": "n#network.com", "type": "Manager" },
{ "id": "21", "name": "abc", "email": "abc#network.com", "type": "Employ" },
{ "id": "52", "name": "abcded", "email": "abcded#network.com", "type": "Manager" }
]
pref = {1: 'owner', 2: 'Manager', 3: 'employ', 4: 'HR' }
choice = 1
idx1 = -1
for each1 in list_1:
idx1 += 1
for each2 in list_2:
if each1['email'] == each2['email']:
print(list_1[idx1]['type'])
print(pref[choice])
list_1[idx1]['type'] = pref[choice]
print(list_1)
Hi I have two dictionaries 1.Primary, 2. Secondary
Need to check first field of both dictionary
If field is same compare the title with primary and secondary
*If field and title is same then From Primary dictionary add count to secondary dictionary
Primary dictionary
{"Latest":[
{
"name": "Employee",
"field": "employee",
"values": [
{
"title": "A",
"paragraph": "null",
"count": "1"
},
{
"title": "C",
"paragraph": "null",
"count": "1"
}
]
},
{
"name": "Project",
"field": "project",
"values": [
{
"title": "NEW_York",
"paragraph": "null",
"count": "3"
}
]
},
{
"name": "Designation",
"field": "designation",
"values": [
{
"title": "Developer",
"paragraph": "null",
"count": "1"
}
]
}
]}
Secondary dictionary
[
{
"name": "Employee",
"field": "employee",
"values": [
{
"title": "A",
"paragraph": "null",
"count": "null"
},
{
"title": "B",
"paragraph": "null",
"count": "null"
}
]
},
{
"name": "Project",
"field": "project",
"values": [
{
"title": "NEW_York",
"paragraph": "test",
"count": "null"
}
]
},
{
"name": "Designation",
"field": "designation",
"values": [
{
"title": "Tester",
"paragraph": "null",
"count": "null"
}
]
}
]
Expected out
{"Latest":[
{
"name": "Employee",
"field": "employee",
"values": [
{
"title": "A",
"paragraph": "null",
"count": "1"
},
{
"title": "C",
"paragraph": "null",
"count": "1"
},
{
"title": "B",
"paragraph": "null",
"count": "null"
}
]
},
{
"name": "Project",
"field": "project",
"values": [
{
"title": "NEW_York",
"paragraph": "null",
"count": "3"
}
]
},
{
"name": "Designation",
"field": "designation",
"values": [
{
"title": "Developer",
"paragraph": "null",
"count": "1"
},
{
"title": "Tester",
"paragraph": "null"
"count": "null"
}
]
}
]}
COde
for primary_elem in primary['Latest']:
primary_titles = [value['title'] for value in primary_elem['values']]
for secondary_elem in secondary:
if secondary_elem['field'] == primary_elem['field']:
for secondary_value in secondary_elem['values']:
if secondary_value['title'] in primary_titles:
for value in primary_elem['values']:
if secondary_value['title'] == value['title']:
secondary_value['count'] = value['count']
got error string element must be integers
How to reduce one loop also 6 to 5
Change
for primary_elem in primary['Latest']:
primary_titles = [value['title'] for value in primary_elem['values']]
for secondary_elem in secondary:
if secondary_elem['field'] == primary_elem['field']:
for secondary_value in secondary_elem['values']:
if secondary_value['title'] in primary_titles:
secondary_elem['count'] = primary_elem['count']
To
for buttfart_junior in primary['Latest']:
buttfart_senior = [value['title'] for value in buttfart_junior['values']]
for young_buttfart in secondary:
if young_buttfart['field'] == buttfart_senior['field']:
for buttfart_farts in buttfart_junior['values']:
if buttfart_farts['title'] in buttfart_senior:
buttfart_junior['count'] = buttfart_senior['count']
I have a Python script where I would like to filter Python with a http get and I would like to filter the response data for only specific values. The json response example is below:
{
"id": "38",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "105600",
"type": "csv",
"status": "Completed",
"creator": {
"id": "1",
"username": "btest",
"firstname": "bob",
"lastname": "test"
},
{
"id": "39",
"name": "Report2",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113218",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
},
"id": "49",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113219",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
}
I would like to filter the above json to only show a report by name. For example if there is a Python filter that would only allow me to filter for a report by the name of "Report1". If I filtered on name of "Report1". I would expect to following to be to be returned below:
{
"id": "38",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "105600",
"type": "csv",
"status": "Completed",
"creator": {
"id": "1",
"username": "btest",
"firstname": "bob",
"lastname": "test"
},
"id": "49",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113219",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
}
For the final part of the script I would like to compare the 'id' field to show the largest value for example id 38 vs id 49 and then output the json for the largest in this case id 49. I would like it output
},
"id": "49",
"name": "Report1",
"description": "",
"reportDefinitionID": "-1",
"jobID": "113219",
"type": "csv",
"status": "Completed"
"creator": {
"id": "1",
"username": "btest1",
"firstname": "Bob",
"lastname": "test1"
}
For the last part i would just like to save the id value '49' to a variable in Python.
So far what I have below is:
response_data = response.json()
input_dict = json.dumps(response_data)
input_transform = json.loads(input_dict)
# Filter python objects with list comprehensions
sort1 = sorted([r.get("id") for r in input_transform if r.get("name") == "Report1"], reverse=True)[0]
# Print sorted JSON
print(sort1)
I updated my code and now I'm getting the error below:
'str' object has no attribute 'get'
I researched it and can not figure out what I'm doing now and how to get past it.
You need to get the ID in the listcomp as bellow:
sorted([r.get("id") for r in sample if r.get("name") == "Report1"], reverse=True)[0]
{
"id": "9",
"children": [{
"id": "8",
"children": [{
"id": "7",
"children": [{
"id": "6",
"children": [
{
"id": "0",
"type": "isPathForward"
},
{
"id": "2",
"children": [{
"id": "1",
"type": "maze_moveForward"
}],
"type": "DO"
},
{
"id": "5",
"children": [{
"id": "4",
"children": [{
"id": "3",
"type": "turnLeft"
}],
"type": "maze_turn"
}],
"type": "ELSE"
}
],
"type": "maze_ifElse"
}],
"type": "DO"
}],
"type": "maze_forever"
}],
"type": "program"
}
The above valid JSON is basically an AST (Abstract Syntax Tree) and I want to extract only the "type" in the order : 1) node followed by 2) Left child and then 3) Right child
Exactly like below for the above JSON :
Program
maze_forever
DO
maze_ifElse
isPathforward
Do
maze_moveForward
Else
maze_turn
turn_Left
I have not worked with json I tried using generators in python but the order is lost in the process as it converts to a dict.
Could you write a python implementation for this ?
UPDATE !!!!
So far i have tried :
import json
json_string= json.loads(above json)
when i type :
for i in json_string:
... print(i)
...
OUTPUT
type
id
children
I also tried
import pandas as pd
d=pd.read_json('{ "id": "9", "children": [{ "id": "8", "children": [{ "id": "7", "children": [{ "id": "6", "children": [ { "id": "0", "type": "isPathForward" }, { "id": "2", "children": [{ "id": "1", "type": "maze_moveForward" }], "type": "DO" }, { "id": "5", "children": [{ "id": "4", "children": [{ "id": "3", "type": "turnLeft" }], "type": "maze_turn" }], "type": "ELSE" } ], "type": "maze_ifElse" }], "type": "DO" }], "type": "maze_forever" }], "type": "program"}')
>>> d
output :
children id type
0 {'type': 'maze_forever', 'id': '8', 'children'... 9 program
Both cases above :
I do not know how to recursively get inside children as every child has one or more children inside. Most answers I searched donot explain for a JSON that is as nested as my JSON above.
The most obvious implementation is as a recursive function:
>>> def process(data):
... if 'type' in data: print data['type']
... if 'children' in data:
... for child in data['children']:
... process(child)
...
>>> j = json.load(open('test.json', 'r'))
>>> process(j)
program
maze_forever
DO
maze_ifElse
isPathForward
DO
maze_moveForward
ELSE
maze_turn
turnLeft
Note that we're printing the current structure's type before we recurse into children.