I intend to get the values for each dictionary in array list and put the values in new dictionary.
There are two key,two values in each dictionary.
This is my array_list.
[{'Name': 'email',
'Value': 'mail#outlook.com'},
{'Name': 'name',
'Value': 'tester'},
{'Name': 'address',
'Value': 'abc'}]
My expected outcome (to get the both values in each dictionary):
{'email': 'mail#outlook.com',
'name': 'tester',
'address': 'abc'}
My current code:
outcome = {}
x = ""
for i in range(len(array_list)):
for key,value in array_list[i].items():
if key == 'Value':
x = value
elif key == 'Name':
outcome[value] = x
I still not able to get the expected outcome. Any helps?
l = [{'Name': 'email',
'Value': 'mail#outlook.com'},
{'Name': 'name',
'Value': 'tester'},
{'Name': 'address',
'Value': 'abc'}]
{k['Name'] : k['Value'] for k in l}
the result is
{'address': 'abc', 'email': 'mail#outlook.com', 'name': 'tester'}
You are almost correct. Just have some problems in if else.
After writing a code you should try to simulate your code by yourself. Please look carefully in you inner for loop. For each iteration either Name or Value will be set as if and elif is mutually exclusive. But the requirement is to create key-value in each iteration.
outcome = {}
array_list = [{'Name': 'email',
'Value': 'mail#outlook.com'},
{'Name': 'name',
'Value': 'tester'},
{'Name': 'address',
'Value': 'abc'}]
for i in range(len(array_list)):
keys = array_list[i].keys()
if 'Name' in keys and 'Value' in keys:
outcome[array_list[i]['Name']] = array_list[i]['Value']
It is almost same as your code but my thinking is different.
Related
This question already has answers here:
Getting a map() to return a list in Python 3.x
(11 answers)
Closed last month.
tbl_headers = db_admin.execute("SELECT name, type FROM PRAGMA_TABLE_INFO(?);", table_name)
tbl_headers is same below:
[{'name': 'id', 'type': 'INTEGER'}, {'name': 'abasdfasd', 'type': 'TEXT'}, {'name': 'sx', 'type': 'TEXT'}, {'name': 'password', 'type': 'NULL'}, {'name': 'asdf', 'type': 'TEXT'}]
I need apply hash_in() function on the 'name' values are in dictionary elements of above list.
Have tried these:
tbl_headers = [hash_in(i['name']) for i in tbl_headers]
suppresses dictionaries and return only a list of 'name' values:
['sxtw001c001h', 'sxtw001c001r001Z001e001c001r001Z001a001Z', 'sxtw001w001r', 'sxtw001c001q001n001v001r001r001Z001o', 'sxtw001e001c001r001Z']
OR
tbl_headers = map(hash_in, tbl_headers)
Returns error.
Update
The Output result I have seek is same:
[{'name': hash_in('id'), 'type': 'INTEGER'}, {'name': hash_in('abasdfasd'), 'type': 'TEXT'}, {'name': hash_in('sx'), 'type': 'TEXT'}, {'name': ('password'), 'type': 'NULL'}, {'name': ('asdf'), 'type': 'TEXT'}]
Appreciate you.
Try this list comprehension:
tbl_headers = [{'name': hash_in(i['name']), 'type': i['type']} for i in tbl_headers]
i have a list of dict like this
[
{'id': 'A123',
'feature': {'name': 'jack', 'age' : '18' },
'create_time': '2022-5-17 10:29:47',
'is_fast': False},
{'id': 'A123',
'feature': {'gender': 'male'},
'create_time': '2022-5-17 10:29:47',
'is_fast': False},
{'id': 'A123',
'habit': {'name': 'read'},
'create_time': '2022-5-15 10:29:45',
'is_fast': False},
{'id': 'A456',
'feature': {'name': 'rose'},
'create_time': '2022-4-15 10:29:45',
'is_fast': False},
{'id': 'A456',
'habit': {'name': 'sport'},
'create_time': '2022-3-15 10:29:45',
'is_fast': False}
]
But I want to merge the same "id" values together using something function
The desired output is as follows
[
{'id': 'A123',
'feature': {'name': 'jack', 'age' : '18' ,'gender': 'male'},
'habit': {'name': 'read'},
'create_time': '2022-5-19 10:29:47', #Get the latest time based on the same id
'is_fast': False},
{'id': 'A456',
'feature': {'name': 'rose'},
'habit': {'name': 'sport'},
'create_time': '2022-4-15 10:29:45',
'is_fast': False},
]
How can I merge the same "id" values according to these dictionaries..
This should get you started... I put some inline notes to explain what the code is doing. You still need to implement a date time comparison.
def merge_dicts(lst):
final = {} # results
for row in lst: # iterate through list
if row['id'] not in final: # if current item id hasnt been seen
final[row['id']] = row # assign it to results with id as the key
else:
record = final[row['id']] # otherwise compare to data already stored
for k,v in row.items(): #iterate through dictionary items
if k not in record: # if key not in results
record[k] = v # add the key and value
continue
if record[k] == v: continue # if they are already equal move on
if isinstance(v, dict): # if its a dictionary
record[k].update(v) # update the dictionary
else: # must be date time sequence so do some datetime comparison
"""Do some date comparison and assign correct date"""
return [v for k,v in final.items()] # convert to list
print(merge_dicts(lst))
output:
[
{
'id': 'A123',
'feature': {'name': 'jack', 'age': '18', 'gender': 'male'},
'create_time': '2022-5-17 10:29:47',
'is_fast': False,
'habit': {'name': 'read'}
},
{
'id': 'A456',
'feature': {'name': 'rose'},
'create_time': '2022-4-15 10:29:45',
'is_fast': False,
'habit': {'name': 'sport'}
}
]
You can use the dict.setdefault method to initialize sub-dicts under keys that don't already exist to avoid cluttering up your code with conditional statements that test the existence of keys:
merged = {}
for d in lst:
s = merged.setdefault(d['id'], d)
for k, v in d.items():
if isinstance(v, dict):
s.setdefault(k, v).update(v)
elif v > s[k]: # the dates/times in the input follow alphabetical order
s[k] = v # later dates/times takes precedence
print(list(merged.values()))
Demo: https://replit.com/#blhsing/BlandCarelessPolygons#main.py
How can I print a list without the first square brackets?
[[{'id': '5b0cecebc15ae360393438c2', 'owner': {'id': '58ebd0b12c593e5253505ad4'}, 'linked_id': None, 'type': 'product', 'name': 'Трансформаторное масло Т-1500у'}]]
At the same time, it is necessary to preserve its essence of the list.
So that the parser can read the id.
items = response['data']
usr_ids = items[i]["owner"]["id"]
Simply print the first item of the list
lst = [[{'id': '5b0cecebc15ae360393438c2', 'owner': {'id': '58ebd0b12c593e5253505ad4'}, 'linked_id': None, 'type': 'product', 'name': 'Трансформаторное масло Т-1500у'}]]
print(lst[0])
I have below boto3 which gives list of dicts with key, value pairs.
service_paginator = ecs_client.get_paginator('list_services')
for page in service_paginator.paginate(cluster=cluster_name,
launchType='FARGATE'):
# print(page)
for service in page['serviceArns']:
response = ecs_client.list_tags_for_resource(resourceArn=service)['tags']
This dict has multiple keys, value pairs. in the below sample format:
Row-1:[{'key': 'Platform', 'value': 'XX'}, {'key': 'StackVersion', 'value': '1.0.1'},{'key': 'ResourceOwner', 'value': 'TeamA'}, {'key': 'Stackname', 'value': 'myfargate-1'}, {'key': 'Service', 'value': 'Processing'}, {'key': 'Name', 'value': 'someName'},{'key': 'deploy_date', 'value': '2021-07-12'}, {'key': 'Source', 'value': 'somesource'}]
Row-2:[{'key': 'Platform', 'value': 'XX'}, {'key': 'StackVersion', 'value': '1.0.1'},{'key': 'ResourceOwner', 'value': 'TeamA'}, {'key': 'Stackname', 'value': 'myfargate-1'}, {'key': 'Service', 'value': 'Processing'}, {'key': 'Name', 'value': 'someName'},{'key': 'deploy_date', 'value': '2021-07-12'}]
Row-3:[{'key': 'Platform', 'value': 'XXY'}, {'key': 'StackVersion', 'value': '1.0.1'},{'key': 'ResourceOwner', 'value': 'TeamA'}, {'key': 'Stackname', 'value': 'myfargate-1'}, {'key': 'Service', 'value': 'Processing'}, {'key': 'Name', 'value': 'someName'},{'key': 'deploy_date', 'value': '2021-07-12'}, {'key': 'Source', 'value': 'somesource'}]
From this lists, I would like to print the service, where in the dict 'key' == 'Platform' and 'key' == 'Source' present. So output should be Row-1 and Row-3 , as ROw-2 doesn't have key called source.
for one key it's ok, but if I have to check multiple keys then it gives me ZERO count.
Is there any pythonic way to do it for more than one key?
I will answer this to myself, but I personally don't like this solution, if anyone has any better solution, please post it here.
service_paginator = ecs_client.get_paginator('list_services')
for page in service_paginator.paginate(cluster=cluster_name,
launchType='FARGATE'):
# print(page)
for service in page['serviceArns']:
response = ecs_client.list_tags_for_resource(resourceArn=service)['tags']
tags = {}
for item in response:
tags[item['key']] = item['value']
if 'Platform' in tags and 'Source' in tags:
platform_name.append(tags['Platform'])
print(set(platform_name)) # to print the unique platform_name
I am trying to build dictionaries (one contains all common elements and the other one contains the different elements) out of a list of dictionaries.
Now I've managed to get it working for a list of 2 dictionaries by converting to a set of tuples and then getting the unique keys as well as the differences with the intersection and difference methods but I don't know how to go about a list of varying length (sometimes I'll have 3 or 4 dictionaries in my list).
I'm sure I need to use map or reduce/lambda function but I can't figure it out.
This is my input:
all_maps = [
[{'key': 'target', 'value': 'true'},
{'key': 'region_name', 'value': 'europe'},
{'field': 'AccessToken', 'key': 'token','path': 'test/path'}],
[{'key': 'target', 'value': 'true'},
{'key': 'region_name', 'value': 'usa'},
{'field': 'AccessToken', 'key': 'token', 'path': 'test/path'}],
[{'key': 'target', 'value': 'true'},
{'key': 'region_name', 'value': 'japan'},
{'field': 'AccessToken', 'key': 'token', 'path': 'test/path'}]
]
What I want is to get 4 dictionaries as such:
intersection = {'key': 'target', 'value': 'true'},
{'field': 'AccessToken', 'key': 'token', 'path': 'test/path'}
diff1 = {'key': 'region_name', 'value': 'europe'}
diff2 = {'key': 'region_name', 'value': 'usa'}
diff3 = {'key': 'region_name', 'value': 'japan'}
A simple answer would be to flatten the all_maps list and separate each items based on its list.count() value:
def flatten(map_groups):
items = []
for group in map_groups:
items.extend(group)
return items
def intersection(map_groups):
unique = []
items = flatten(map_groups)
for item in items:
if item not in unique and items.count(item) > 1:
unique.append(item)
return unique
def difference(map_groups):
unique = []
items = flatten(map_groups)
for item in items:
if item not in unique and items.count(item) == 1:
unique.append(item)
return unique
Here's the output using these functions:
>>> intersection(all_maps)
[{'key': 'target', 'value': 'true'},
{'field': 'AccessToken', 'key': 'token', 'path': 'test/path'}]
>>> difference(all_maps)
[{'key': 'region_name', 'value': 'europe'},
{'key': 'region_name', 'value': 'usa'},
{'key': 'region_name', 'value': 'japan'}]
For a more advanced implementation, you can look into set().