list of dict with same key name - python-3.x

I am trying to achieve the following output:
[{'Key': 'Language', 'Value': 'Python'}, {'Key': 'Version', 'Value': '3.7'}]
I have implemented a method to achieve the above output:
#cli.command('test', context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True
))
#click.pass_context
def test(ctx):
data = dict()
tags=dict()
tag_list = list()
for item in ctx.args:
data.update([item.split('=')])
for items in data.items():
tags['Key'] = items[0]
tags['Value'] = items[1]
tag_list.append(tags)
print(tag_list)
Method Call:
python test.py test Language=Python Version=3.7
But I am getting below output:
[{'Key': 'Version', 'Value': '3.7'}, {'Key': 'Version', 'Value': '3.7'}]
The is old dict is been replaced and then appended.
Can you please help me with this?
Thanks & Regards,

You are mutating the same dict in the last loop, so your list will have references to the same dict.
Move this:
tags=dict()
...inside the final for loop:
for items in data.items():
tags=dict()

Related

How to access key and value from this dictionary

Here is a snippet of function code in Python:
def restart_lab_server(aws_client):
response = aws_client.describe_instances()
###print(response)
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
# This sample print will output entire Dictionary object
# This will print will output the value of the Dictionary key 'InstanceId'
try:
print(instance["Tags"])
except:
print("This instance does not have any tags.")
print("Next Entry.")
return 0
The output that I am getting this the following:
[{'Key': 'Name', 'Value': 'EC2-Nessus-AmazonLinux2'}]
[{'Key': 'Name', 'Value': 'LCE Server'}]
[{'Key': 'Name', 'Value': 'Windows-2019-xxxxx'}]
[{'Key': 'Name', 'Value': 'SecurityCenter-Lab-5.19.1'}]
[{'Key': 'Name', 'Value': 'Nessus-Target-Lab'}]
[{'Key': 'Name', 'Value': 'Nessus-Agent-Lab'}]
[{'Key': 'Name', 'Value': 'NNM-Lab'}]
[{'Key': 'Name', 'Value': 'WindowsInstance'}]
This instance does not have any tags.
Next Entry.
[{'Key': 'CfStackId', 'Value': 'arn:aws:cloudformation:us-east-1:581987831513:stack/Nessus-Thomas-101-2/41d38410-5729-11ed-a52f-127af16651f7'}, {'Key': 'aws:cloudformation:stack-id', 'Value': 'arn:aws:cloudformation:us-east-1:581987831513:stack/Nessus-Thomas-101-2/41d38410-5729-11ed-a52f-127af16651f7'}, **{'Key': 'NessusScanner', 'Value': 'TRUE'},** {'Key': 'aws:cloudformation:logical-id', 'Value': 'NessusEC2Instance'}, {'Key': 'aws:cloudformation:stack-name', 'Value': 'Nessus-Thomas-101-2'}]
My main interest is to get "{'Key': 'NessusScanner', 'Value': 'TRUE'},"
I can't seem to extract this or not sure how to. I am not sure if I need to use a linescanner or something else.
I'm trying to restart all Nessus scanners in my and figured using key and value Nessus scanner True.
Please note, I'm using
describe_instances()
I have tried creating another for loop but keep getting an error message.
Found the answer or workaround:
def restart_lab_server(aws_client):
response = aws_client.describe_instances()
###print(response)
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
try:
x = instance["Tags"]
for y in x:
print(y["Value"])
except:
print("This instance does not have any tags. Next Entry.")
return 0

convert list of dictionary values in to list of values

Hi all below is my list of dictionary
a=[{'Name': 'dhaya', 'Place': 'pune', 'Designation': 'fleetEngineer'},
{'Name': 'rishi', 'Place': 'maharastra', 'Designation': 'Sr.Manager'}]
iam expecting output like this
a={"Name":["dhaya","rishi],"Place":["pune","maharastra"],Designation:["fleetEngineer","Sr.Manager"]
"}
can any one assist
new_dict is the answer to the question you posted. Its the smallest and simplest.
b = list(a[0].keys())
new_dict = {}
for x in b:
new_dict[x] = [l[x] for l in a]
print('My expected dictionary',new_dict)
One can use nested for loops for this:
inputList = [{'Name': 'dhaya', 'Place': 'pune', 'Designation': 'fleetEngineer'}, {
'Name': 'rishi', 'Place': 'maharastra', 'Designation': 'Sr.Manager'}]
outputDict = {}
for origDict in inputList:
for key, val in origDict.items():
if key in outputDict:
outputDict[key].append(val)
else:
outputDict[key] = [val]
print(outputDict)
a=[{'Name': 'dhaya', 'Place': 'pune', 'Designation': 'fleetEngineer'}, {'Name': 'rishi', 'Place': 'maharastra', 'Designation': 'Sr.Manager'}]
Name = []
Place = []
Designation = []
for ele in a:
Name.append(ele["Name"])
Place.append(ele["Place"])
Designation.append(ele["Designation"])
new_a = {}
new_a['Name'] = Name
new_a['Place'] = Place
new_a["pune"] = Designation
print(new_a)

How to get a dict from a list of dict according to some threshold

I have a list of dicts like the one below:
list_dict = [{'Name': 'Andres', 'score': 0.17669814825057983},
{'Name': 'Paul', 'score': 0.14028045535087585},
{'Name': 'Feder', 'score': 0.1379694938659668},
{'Name': 'James', 'score': 0.1348174512386322}]
I want to output another list of dict but only when sum of score is higher than a threshold=0.15
Expected output: [{'name':'Andres', 'score' : 0.1766..}]
I did this, but the code is terrible and the outuput is wrongly formatted
l = []
for i in range(len(list_dict)):
for k in list_dict[i]['name']:
if list_dict[i]['score']>0.15:
print(k)
Maybe this is what you're looking?
Actually you're very close... but just miss a few syntax.
Each item in list_dict is a dictionary, so you can access and ask the score, it should not use index to get the interesting part.
new_dc = list()
for item in list_dict: # each item is a dictionary
if item['score'] > 0.15: # it's better to use a meaningful variable.
new_dc.append(item)
print(new_dc) # [{'Name': 'Andres', 'score': 0.17669814825057983}]
Alternatively you can use List Comprehension:
output = [item for item in list_dict if item['score'] > 0.15]
assert new_dc == output # Silence mean they're the same
1st approach using loop
final_list = []
for each in list_dict: #simply iterate through each dict in list and compare score
if each['score']>0.15:
final_list.append(each)
print(final_list)
2nd approach using list comprehension
final_list = [item for item in list_dict if item['score']>0.15]
print(final_list)

How to append the repeated values to same key in dictionary list

I have below dictionary list which contains repeated values. i need to append the repeated values to same key and remain should store as it in the dictionary list.
veh_entry=[{'name': 'scott', 'id': '17'},{'name': 'thomas', 'id': '18'}, {'name': 'tony', 'id': '17'}]
i tried with below approach, but not seems to be working as expected
add=[]
test={}
for item in veh_entry:
if item['id'] not in add:
test['name']=item['name']
add.append(item['id'])
else:
test['name']=(test['name']+ ','+item['name'])
#expected:
the expected dictionary must be as follows:
[{'name': 'scott, tony', 'id':'17'},{'name': 'thomas', 'id': '18'}]
So the basic logic was to compare the ids of different item in the list and if the id's match then join the name and remove the repeated item from the list
final_result = []
for i in range(len(veh_entry)-1):
for j in range(i+1,len(veh_entry)):
a = dict()
if veh_entry[i]['id'] == veh_entry[j]['id']:
a['name'] = veh_entry[i]['name'] +','+veh_entry[j]['name']
a['id'] = veh_entry[i]['id']
veh_entry.pop(j)
final_result.append(a)
else:
final_result.append(veh_entry[j])
print(final_result)
Output:- [{'name': 'thomas', 'id': '18'}, {'name': 'scott,tony', 'id': '17'}]
You can go with this:
def remove_dup(arr):
names=[] # using list here
ids=[] # instead of dict
for x in arr:
id,name=x['id'],x['name']
if id not in ids: # search for existing id
ids.append(id)
names.append(name)
else:
names[ids.index(id)]+=", "+name
return [{'name':name,'id':id} for name,id in zip(names,ids)]
veh_entry=[{'name': 'scott', 'id': '17'},{'name': 'thomas', 'id': '18'}, {'name': 'tony', 'id': '17'}]
print(remove_dup(veh_entry))

how to convert dict value use lambda map in python

the format data like this, To explain, I have this dict:
{
'41': [
'1029136700',
'1028348931'
],
'42': ['12234454']
...
}
then i want to convert the format like this used lambda and map:
[
{
'key':'41','value':'1029136700'
},
{
'key':'41','value': '1028348931'
},
{
'key':'42', 'value': '12234454'
}
...
]
Can you give me a clue on how to achieve this in python?
Here is a clue on how to get what you want - you have to iterate over the initial dictionary:
for key, list_of_vals in initial_dictionary.items():
for val in list_of_vals:
# now you have pairs
# for example, key = '41', val = '1029136700'
# use them as you need
Just couple more steps and you get exactly what you want.
However, if you want to do this with map() and lambda it would not be that easy. You have to replace every for loop (there 2 of them) with map() containing lambda. map() returns generator so you have to iterate over it to get actual result, for example, list(map(...)). Here is complete code how you can get what you want:
result = list()
set(map(lambda item: result.extend(list(
map(lambda val: {'key': item[0], 'value': val},
item[1]))),
initial_dictionary.items()))
print(result)
Output:
[{'key': '41', 'value': '1029136700'}, {'key': '41', 'value': '1028348931'}, {'key': '42', 'value': '12234454'}]
This implementation is significantly more difficult to read and understand.

Resources