This is my json :
{'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}
I want to get a list of all the values of name.
What should be my code in python
d.values gives all the values, then you can get the attribute name of each value.
d = {'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}
[i['name'] for i in d.values()]
['poulami', 'test']
Also note that d.values returns a generator and not a list so to convert to list use list(d.values())
That is not JSON format. It is a Python Dictionary.
Iterate over the values of the dictionary(d.values()) and get the name from each item.
d = {'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}
names_list = []
for i in d.values():
names_list.append(i['name'])
names_list = ['poulami', 'test']
Related
I want to remove duplicates values from list which is inside the dictionary. I am trying to make configurable code to work on any field instead of making field specific.
Input Data :
{'Customer_Number': 90617174, 'Email': [{'Email_Type': 'Primary', 'Email': ['saman.zonouz#rutgers.edu', 'saman.zonouz#rutgers.edu']}], 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280, 12177218280]}]}
Expected Output Data :
{'Customer_Number': 90617174, 'Email': [{'Email_Type': 'Primary', 'Email': ['saman.zonouz#rutgers.edu']}], 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280]}]}
code tried:
dic = {'Customer_Number': 90617174, 'Email': [{'Email_Type': 'Primary', 'Email': ['saman.zonouz#rutgers.edu', 'saman.zonouz#rutgers.edu']}], 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280, 12177218280]}]}
res = []
for i in dic:
if i not in res:
res.append(i)
You can use set()
import json
dic = {
'Customer_Number': 90617174,
'Email': [
{
'Email_Type': 'Primary',
'Email': list(set([
'saman.zonouz#rutgers.edu',
'saman.zonouz#rutgers.edu',
]))
}
],
'Phone_Number': [
{
'Phone_Type': 'Mobile',
'Phone': list(set([
12177218280,
12177218280,
]))
}
]
}
print(json.dumps(dic,indent=2))
If you want to do it on a list of dic's then you can do like this:
for dic in dics:
for email in dic['Email']:
email['Email'] = list(set(email['Email']))
for phone in dic['Phone_Number']:
phone['Phone'] = list(set(phone['Phone']))
The approach that you started with, you need to go a few levels deeper with that to find every such "repeating" list and dedupe it.
To dedupe, you can use a set - which is also a "container" data structure like a list but with some (many?) differences. You can get a good introduction to all of this in the official python docs -
for key in dic:
if isinstance(dic[key], list):
for inner_dict in dic[key]:
for inner_key in inner_dict:
if isinstance(inner_dict[inner_key], list):
inner_dict[inner_key] = list(set(inner_dict[inner_key]))
print(dic)
#{'Customer_Number': 90617174,
# 'Email': [{'Email_Type': 'Primary', 'Email': ['saman.zonouz#rutgers.edu']}],
# 'Phone_Number': [{'Phone_Type': 'Mobile', 'Phone': [12177218280]}]}
I'm looking to parse the following dictionary received json response and am running into issues. My dictionary name is results.
This is a simple json response that appears to be dict.
{'resultType': 'vector', 'result': [{'metric': {'agent_host': 'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch', 'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance': 'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack', 'site_name': 'test_site'}, 'value': [1631917506.324, '0.00009262475396549728']}]}
Type confirms that:
<class 'dict'>
Ultimately what I'd like to do is something along the lines of:
for key, value in results.items():
(rx_error, rx_error_freq) = value[16]
In order to get the value 0.00009262475396549728 from above. How would I go about doing this?
One great way to visualize nested dictionaries is to use pprint which comes built into python3
from pprint import pprint
d = {'resultType': 'vector', 'result': [{'metric': {'agent_host':
'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch',
'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance':
'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack',
'site_name': 'test_site'}, 'value': [1631917506.324,
'0.00009262475396549728']}]}
pprint(d)
>>> {'result': [{'metric': {'agent_host': 'x.x.x.x',
'cluster_name': 'test_cluser',
'device_type': 'switch',
'hostname': 'myswitch',
'ifName': 'xe-0/0/10',
'instance': 'telegraf:1111',
'job': 'telegraf',
'rack_name': 'test_rack',
'site_name': 'test_site'},
'value': [1631917506.324, '0.00009262475396549728']}],
'resultType': 'vector'}
This allows us to see the different key value pairs a lot more easily. So the data you're looking to access would is
rx_error, rx_error_freq = d["result"][0]["value"]
Loop over the result list to get the value, then print the second element
>>> data = {'resultType': 'vector', 'result': [{'metric': {'agent_host': 'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch', 'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance': 'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack', 'site_name': 'test_site'}, 'value': [1631917506.324, '0.00009262475396549728']}]}
>>> for r in data['result']:
... print(r['value'][1])
...
0.00009262475396549728
I am looping over the json object and output of the object is in the form of lists of dictionaries.
[{'Status': 'active', 'id': '0f1fb86da9c7ee380'}]
[{'Status': 'active', 'id': '0d6b330e4960c3382'}, {'Status': 'active', 'id': '033cfb634e595ccfa'}]
[{'Status': 'active', 'id': '0457f623cbb9f7c95'}]
[{'Status': 'active', 'id': '01b69eb6a3048f749'}, {'Status': 'active', 'id': '0f7ce44a9a5fc82f5'}, {'Status': 'active', 'id': '05417e161acf3ec5d'}]
[{'Status': 'active', 'id': '033cfb634e595ccfa'}, {'Status': 'active', 'id': '01eab32f9808acf19'}]
I have tried something like this so far but it prints in the form of string. I tried using list and appending it but it gives me a weird output. If I don't use list then it gives me the list of all in the form of strings.
Current output:
0f1fb86da9c7ee380
0d6b330e4960c3382
033cfb634e595ccfa
0457f623cbb9f7c95
01b69eb6a3048f749
0f7ce44a9a5fc82f5
05417e161acf3ec5d
0f373f123dc8221de
05417e161acf3ec5d
My code:
for i in data['DBI']:
t = 0
while t < len(i['Groups']):
print i['Groups'][t]['id']
t += 1`
Expected Output: I am looking for the output in the form of the list like this ['0f1fb86da9c7ee380'] ['0d6b330e4960c3382','033cfb634e595ccfa'] ['0457f623cbb9f7c95'] ['01b69eb6a3048f749','0f7ce44a9a5fc82f5',''05417e161acf3ec5d'] ['033cfb634e595ccfa','01eab32f9808acf19']
What you want is something like this:
data = [
[{'Status': 'active', 'id': '0f1fb86da9c7ee380'}],
[{'Status': 'active', 'id': '0d6b330e4960c3382'}, {'Status': 'active', 'id': '033cfb634e595ccfa'}],
[{'Status': 'active', 'id': '0457f623cbb9f7c95'}],
[{'Status': 'active', 'id': '01b69eb6a3048f749'}, {'Status': 'active', 'id': '0f7ce44a9a5fc82f5'}, {'Status': 'active', 'id': '05417e161acf3ec5d'}],
[{'Status': 'active', 'id': '033cfb634e595ccfa'}, {'Status': 'active', 'id': '01eab32f9808acf19'}],
]
new_data = []
for l in data:
current_ids = []
for d in l:
current_ids.append(d["id"])
new_data.append(current_ids)
new_data
output:
[['0f1fb86da9c7ee380'],
['0d6b330e4960c3382', '033cfb634e595ccfa'],
['0457f623cbb9f7c95'],
['01b69eb6a3048f749', '0f7ce44a9a5fc82f5', '05417e161acf3ec5d'],
['033cfb634e595ccfa', '01eab32f9808acf19']]
You can also use list comprehension to achieve this.
output = [[item["id"] for item in items] for items in data]
data =json.loads(v_string)
for id in data['DBI']:
datalist = id['Groups']
i=0
data_list=[] #<-- This was outside above mann for loop.
while i < len(datalist):
for dic in datalist[i]:
if 'active' not in datalist[i][dic]:
data_list.append(datalist[i][dic])
print(data_list)
i+=1
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.
I have a python dict that looks like this
{'data': [{'data': [{'data': 'gen1', 'name': 'objectID'},
{'data': 'familyX', 'name': 'family'}],
'name': 'An-instance-of-A'},
{'data': [{'data': 'gen2', 'name': 'objectID'},
{'data': 'familyY', 'name': 'family'},
{'data': [{'data': [{'data': '21',
'name': 'objectID'},
{'data': 'name-for-21',
'name': 'name'},
{'data': 'no-name', 'name': None}],
'name': 'An-instance-of-X:'},
{'data': [{'data': '22',
'name': 'objectID'}],
'name': 'An-instance-of-X:'}],
'name': 'List-of-2-X-elements:'}],
'name': 'An-instance-of-A'}],
'name': 'main'}
The structure is repeating and its rule is like:
A dict contains 'name' and 'data'
'data' can contain a list of dicts
If 'data' is not a list, it is a value I need.
'name' is a just a name
The problem is that for each value, I need to know every info for each parent.
So at the end, I need to print a list with items that looks something like:
objectID=gen2 family=familyY An-instance-of-X_objectID=21 An-instance-of-X_name=name-for-21
Edit: This is only one of several lines I want as the output. I need one line like this for each item that doesn’t have a dict as 'data'.
So, for each data that is not a dict, traverse up, find info and print it..
I don't know every function in modules like itertools and collections. But is there something in there I can use? What is this called (when I am trying to do research on my own)?
I can find many "flatten dict" methods, but not like this, not when I have 'data', 'name' like this..
This is a wonderful example what recursion is good for:
input_ = {'data': [{'data': [{'data': 'gen1', 'name': 'objectID'},
{'data': 'familyX', 'name': 'family'}],
'name': 'An-instance-of-A'},
{'data': [{'data': 'gen2', 'name': 'objectID'},
{'data': 'familyY', 'name': 'family'},
{'data': [{'data': [{'data': '21',
'name': 'objectID'},
{'data': 'name-for-21',
'name': 'name'},
{'data': 'no-name', 'name': None}],
'name': 'An-instance-of-X:'},
{'data': [{'data': '22',
'name': 'objectID'}],
'name': 'An-instance-of-X:'}],
'name': 'List-of-2-X-elements:'}],
'name': 'An-instance-of-A'}],
'name': 'main'}
def parse_dict(d, predecessors, output):
"""Recurse into dict and fill list of path-value-pairs"""
data = d["data"]
name = d["name"]
name = name.strip(":") if type(name) is str else name
if type(data) is list:
for d_ in data:
parse_dict(d_, predecessors + [name], output)
else:
output.append(("_".join(map(str,predecessors+[name])), data))
result = []
parse_dict(input_, [], result)
print "\n".join(map(lambda x: "%s=%s"%(x[0],x[1]),result))
Output:
main_An-instance-of-A_objectID=gen1
main_An-instance-of-A_family=familyX
main_An-instance-of-A_objectID=gen2
main_An-instance-of-A_family=familyY
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_objectID=21
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_name=name-for-21
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_None=no-name
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_objectID=22
I hope I understood your requirements correctly. If you don't want to join the paths into strings, you can keep the list of predecessors instead.
Greetings,
Thorsten