Converting a list of dicts to a single dictionary - python

For below content how can I get "a_id" value and its "b_id" value based on "name" validation.
[
{
"name": "name1",
"a_id": "12345",
"b_id": "0d687c94c5f4"
},
{
"name": "name2",
"a_id": "67890",
"b_id": "0d687c94c5f4"
},
{
"name": "name3",
"a_id": "23857",
"b_id": "9ec34be3d535"
},
{
"name": "name4",
"a_id": "84596",
"b_id": "9ec34be3d535"
},
{
"name": "name5",
"a_id": "d82ebe9815cc",
"b_id": null
}
]
I have used for two values like
{result['a_id']: result['name'] for result in data}
but for third value it won't let me do this if I use like this.
{result['a_id']: result['name'], result['b_id']: result['name'] for result in data}
what is the correct syntax.

I think a dict comprehension with a nested loop should do the trick:
data = {result[k] : result['name'] for result in data for k in ('a_id', 'b_id')}
You can add as many keys as you want. If it makes more sense, declare your keys outside, in a variable keys:
keys = ('a_id', 'b_id', ...)
data = {result[k] : result['name'] for result in data for k in keys}

Related

convert json to csv without keys and put all values in one row

how can i convert from this json-format:
{
"Key1": {
"Value": "123",
"Value": "456",
},
"Key2" : {
"Value": "789",
},
"Key3": {
"Value": "000",
},
"Key4" : {
"Value": "111",
}
}
to this csv-format:
|Col A|Col B|Col C|Col D|Col E|
Row 1|123 |456 |789 |000 |111 |
I want to ignore the keys and just add the values to the csv and all values should be in one row...I donĀ“t need any headers or index. just the values
Assuming that the JSON is fixed to be valid, then you can easily do this with a nested list comprehension:
data = {
"Key1": {
"Value1": "123", # Note: I've fixed your JSON here.
"Value2": "456",
},
"Key2": {
"Value1": "789",
},
"Key3": {
"Value1": "000",
},
"Key4": {
"Value1": "111",
},
}
# In practice this might be in a different data.json file,
# which can then be opened with:
# import json
# with open("data.json", "r") as f:
# data = json.load(f)
# Take the values of the outer dict, and then the values of the inner dict
values = [value for value_dict in data.values() for value in value_dict.values()]
print(values)
# Write to a file by separating with commas
with open("values.csv", "w") as f:
f.write(",".join(values))
This outputs
['123', '456', '789', '000', '111']
and values.csv becomes:
123,456,789,000,111

How to search JSON object and extract the key/value pair?

I'm trying to search a JSON Object and extract the Key/Value pairs for 'name' and 'id' below. I would like to extract all instances of the 'name' and 'id':
{
"response": [
{
"additionalInfo": [],
"id": "b6549916-b8e1-4131-b0be-f4a3daee26fc",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Global",
"siteHierarchy": "b6549916-a8e1-4131-b0be-f4a3daee26fc",
"siteNameHierarchy": "Global"
},
{
"additionalInfo": [
{
"attributes": {
"addressInheritedFrom": "66284774-4ae4-42a1-b27c-68231c98d7db",
"type": "area"
},
"nameSpace": "Location"
}
],
"id": "4ffb292c-4cc8-444b-8978-61b97c6874db",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Peak Tester",
"parentId": "66a84774-4ae4-42a1-b27c-68231c98d7db",
"siteHierarchy": "b6549916-b8e1-4131-b0be-f4a3daee21fc/66a84774-4ae4-42a1-b27c-68231c98d7db/4ffb292c-4cc8-444b-8978-61b97c6874db",
"siteNameHierarchy": "Global/Template Site/Peak Tester"
}
]
}
I have tried several things that are not working.
for elements in site_info['response']:
for item in elements:
if item == 'name':
print(item)
This only prints the output of 'name' and not the value. I would like the value as well as the key.
Simply when you have the key and you need the value, you have to do this:
>>> dictionary['key']
'value'
In your case:
if item == 'name':
print(item['name'])
Anyway you can simply omitt the if statement this way:
for item in elements:
print(item['name'])
I see you already have your answer, which is great.
data = { "response": [ {"name" : "fred"}, {"name" : "tom"}]} # data is a dictionary
arr = data['response'] # arr is a list of dictionaries
for i in arr:
print('name', i['name']) # lookup the name value from each sub-dictionary

How to sort the list of dictionary with repect to time

I have dictionary which is below
{
"id": "98992",
"data": [
{
"app": "Market",
"hash": "ajlfdfd",
"nTime": "2021-02-24 16:03:29.149638"
},
{
"app": "Market",
"hash": "dfds560",
"nTime": "2021-02-25 05:10:09.828576"
},
{
"app": "Market",
"hash": "dfdsfds73",
"nTime": "2021-02-23 15:52:51.954543"
}
]
}
You can see second is dictionary has to come, Latest has to come first
My expect out is same dictionary with Latest time at top
My psedo code is below
def test(mydict):
for key in sorted(mydict):
return (nTime, mydict['nTime'])
NB: I don't want to use Pandas
If your data is stored in variable called data you can use this:
data['data'] = sorted(data['data'], key=lambda x: x['nTime'], reverse=True)

Transforming JSON keys and values

I have a simple json in python that looks like :
{
"list": [{
"key1": "value1"
},
{
"key1": "value1"
}
]
}
I want to transform this to the following json. Any suggestions how I can do it with python without installing additional libraries?
{
"list": [{
"keys": {
"name": "key1",
"value": "value1"
}
}, {
"keys": {
"name": "key1",
"value": "value1"
}
}]
}
Not sure from your question if you already have the json read into a variable, or if it is in a file. This is assuming you have it in a variable already:
in_json = {
"list": [{
"key1": "value1"
},
{
"key2": "value2"
}
]
}
out_json = {"list":[]}
for kd in in_json["list"]:
sub_kd = {"keys": {}}
for k,v in kd.iteritems():
sub_kd["keys"]["name"] = k
sub_kd["keys"]["value"] = v
out_json["list"].append(sub_kd)
print(out_json)
It just loops through the json making dictionaries to append to the out_json dictionary. You could make this print pretty with the json library and also save to file with it
You didn't indicate exactly what contains the JSON data is in, so I've put it all in a string in the example code below and uses the json.loads() function to turn it into a Python dictionary. If it's in a file, you can use the module's json.load() function instead.
It also make the assume that each sub-JSON object in the "list" list consists of only one key/value pair as shown in your question.
The code below changes the deserialized dictionary in-place and pretty-prints the result of doing that by using the json.dumps() function to reserialize it.
Note that I changed the keys and values in sample input JSON slightly to make it easier to see the correspondence between it and the printed results.
import json
json_in = '''
{
"list": [
{
"key1": "value1"
},
{
"key2": "value2"
}
]
}
'''
json_data = json.loads(json_in) # Deserialize.
for i, obj in enumerate(json_data['list']):
# Assumes each object in list contains only one key, value pair.
newobj = { 'name': next(iter(obj.keys())),
'value': next(iter(obj.values()))}
json_data['list'][i] = {'keys': newobj}
print(json.dumps(json_data, indent=4)) # Reserialize and print.
Printed result:
{
"list": [
{
"keys": {
"name": "key1",
"value": "value1"
}
},
{
"keys": {
"name": "key2",
"value": "value2"
}
}
]
}

Django filtering based on list value

My JSON data is in this format..
[
{
"id": "532befe4ee434047ff968a6e",
"company": "528458c4bbe7823947b6d2a3",
"values" : [
{
"Value":"11",
"uniqueId":true
},
{
"Value":"14",
"uniqueId":true
},
]
},
{
"id": "532befe4ee434047ff968a",
"company": "528458c4bbe7823947b6d",
"values" : [
{
"Value":"1111",
"uniqueId":true
},
{
"Value":"10",
"uniqueId":true
},
]
}
]
If I want to filter based on company field then it is possible in this way.
qaresults = QAResult.objects.filter(company= comapnyId)
and it gives me first dictionary of list
But what If I want to filter this based on values list's "value" of Value Key of first dictionary ?
I am not 100% sure what you want , but from what i understand your question,
Try this solution :
import json
json_dict = json.loads('[{"id": "532befe4ee434047ff968a6e","company": "528458c4bbe7823947b6d2a3","values": [{"Value": "11","uniqueId": true},{"Value": "14","uniqueId": true}]},{"id": "532befe4ee434047ff968a","company": "528458c4bbe7823947b6d","values": [{"Value": "1111","uniqueId": true},{"Value": "10","uniqueId": true}]}]')
expected_values = []
js = json_dict[0]
for key,value in js.items():
if key == 'values':
expected_values.append(value[0]['Value'])
And then
qaresults = QAResult.objects.filter(company__id__in = expected_values)

Categories

Resources