I have a list of dictionaries with 2 keys: 'name' & 'value'. I need to get the value of 'value' key if value of 'name' key is 'Subject'
Currently i'm iterating through each dict and checking the value of 'name' and getting the value of 'value'. Is there any improved way of doing this ?
items = [
{
"name": "From",
"value": "from#example.com"
},
{
"name": "Date",
"value": "Tue, 8 Sep 2014 16:18:35 +0530"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "To",
"value": "sender#example.com"
},
]
for item in items:
if item.get('name') == 'Subject':
print "Subject: " + item.get('value')
You should transpose your data into a dict instead:
>>> d = dict([(e['name'],e['value']) for e in items]) # transpose
Or a slightly easier way as mentioned by Peter Wood in the comments:
>>> d = {e['name']: e['value'] for e in items}
Then just use the dict as normal:
>>> d['Subject']
'Test Subject'
You could use next along with a generator filtering and converting the items.
>>> subject = next(field['value']
... for field in items
... if field['name'] == 'Subject')
As Jonas told, better for modify your structure because
from collections import defaultdict
it = [
{
"name": "From",
"value": "from#example.com"
},
{
"name": "Date",
"value": "Tue, 8 Sep 2014 16:18:35 +0530"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "Subject",
"value": "Test Subject 55"
},
{
"name": "To",
"value": "sender#example.com"
},
]
result = defaultdict(list)
# shorcut better to use for...
[result[item["name"]].append(item["value"]) for item in it]
print(result["Subject"])
['Test Subject', 'Test Subject 55']
Related
I have the following list:
{
"id":1,
"name":"John",
"status":2,
"custom_attributes":[
{
"attribute_code":"address",
"value":"st"
},
{
"attribute_code":"city",
"value":"st"
},
{
"attribute_code":"job",
"value":"test"
}]
}
I need to get the value from the attribute_code that is equal city
I've tried this code:
if list["custom_attributes"]["attribute_code"] == "city" in list:
var = list["value"]
But this gives me the following error:
TypeError: list indices must be integers or slices, not str
What i'm doing wrong here? I've read this solution and this solution but din't understood how to access each value.
Another solution, using next():
dct = {
"id": 1,
"name": "John",
"status": 2,
"custom_attributes": [
{"attribute_code": "address", "value": "st"},
{"attribute_code": "city", "value": "st"},
{"attribute_code": "job", "value": "test"},
],
}
val = next(d["value"] for d in dct["custom_attributes"] if d["attribute_code"] == "city")
print(val)
Prints:
st
Your data is a dict not a list.
You need to scan the attributes according the criteria you mentioned.
See below:
data = {
"id": 1,
"name": "John",
"status": 2,
"custom_attributes": [
{
"attribute_code": "address",
"value": "st"
},
{
"attribute_code": "city",
"value": "st"
},
{
"attribute_code": "job",
"value": "test"
}]
}
for attr in data['custom_attributes']:
if attr['attribute_code'] == 'city':
print(attr['value'])
break
output
st
I have a field where value is as below
b = [
{
"category": "Engineer",
"name": "Anthony Test",
"id": 219
},
{
"category": "Engineer",
"name": "Pete Junior",
"id": 220
}
]
I would like to get the result in below format where I want to eliminate category and create a dictionary with id and name
result = {'219': 'Anthony Test', '220': 'Pete Junior'}
You can use dictionary comprehension
{i['id']: i['name'] for i in b}
I need to create a json string like in the example below and I am thinking of using a dict that I can ultimately json.dumps to a json string. I will build this dict in a loop. This is what the json should look like
{
"big-data-list" :[
{
"indexnum": "1",
"components" :
[
{
"key": "some-key1",
"item" :"item name",
"data" :"some string",
}
]
},
{
"indexnum": "2",
"components" :
[
{
"key": "some-key2",
"item" :"item name 2",
"data" :"some string 2",
},
{
"key": "some-key3",
"item" :"item name 3",
"data" :"some string 3",
}
]
}
}
Here is what I tried without a loop to see how things work
bigdata= {}
indexnum= {}
componentList = {}
indexnum["components"] = {}
indexnum["mileage"] = 20
componentList["key"] = "some-key1"
componentList["item"] = "item name"
componentList["data"] = "some string"
indexnum["components"][0] = componentList
componentList["key"] = "some-key2"
componentList["item"] = "item name 2"
componentList["data"] = "some string 2"
indexnum["components"][1] = componentList
print(json.dumps(indexnum))
What I end up getting looks like this:
{"components": {"0": {"key": "somekey2", "item": "fuel2"}, "1": {"key": "somekey2", "item": "fuel2"}}, "mileage": 20}
How do I build the dict so I can json dump it in the way I need to? Is there a better way to come up with such a json object as represented in the example above?
You basically just need to work on your logic to put your data in the appropriate structure of dicts and lists.
Below is an example of a loop that puts some data into the specified structure:
>>> # say you originally have your data in the following list
... lists_of_components = [
... [("some-key1", "item name", "some string")],
... [("some-key2", "item name 2", "some string 2"),
... ("some-key3", "item name 3", "some string 3")],
... ]
... bigdata = {}
... bigdata["big-data-list"] = []
... for i, components in enumerate(lists_of_components, 1):
... bigdata["big-data-list"].append({
... "indexnum": str(i),
... "components": [
... {k: v for k, v in zip(["key", "item", "data"], component)}
... for component in components]
... })
... print(json.dumps(bigdata, indent=4))
{
"big-data-list": [
{
"indexnum": "1",
"components": [
{
"key": "some-key1",
"item": "item name",
"data": "some string"
}
]
},
{
"indexnum": "2",
"components": [
{
"key": "some-key2",
"item": "item name 2",
"data": "some string 2"
},
{
"key": "some-key3",
"item": "item name 3",
"data": "some string 3"
}
]
}
]
}
I have a json that is a list of dictionaries that looks like this:
I am getting it from MySQL with pymysql
[{
"id": "123",
"name": "test",
"group": "test_group"
},
{
"id": "123",
"name": "test",
"group": "test2_group"
},
{
"id": "456",
"name": "test2",
"group": "test_group2"
},
{
"id": "456",
"name": "test2",
"group": "test_group3"
}]
I need to group it so each "name" will have just one dict and it will contain a list of all groups that under this name.
something like this :
[{
"id": "123",
"name": "test",
"group": ["test2_group", "test_group"]
},
{
"id": "456",
"name": "test2",
"group": ["test_group2", "test_group3"]
}]
I would like to get some help,
Thanks !
You can use itertools.groupby for grouping of data.
Although I don't guarantee solution below to be shortest way but it should do the work.
# Your input data
data = []
from itertools import groupby
res = []
key_func = lambda k: k['id']
for k, g in groupby(sorted(data, key=key_func), key=key_func):
obj = { 'id': k, 'name': '', 'group': []}
for group in g:
if not obj['name']:
obj['name'] = group['name']
obj['group'].append(group['group'])
res.append(obj)
print(res)
It should print the data in required format.
New to python here. I'm trying to iterate over all the JSON "group" objects for each person but having some difficulty. This is only a partial list (not all users have groups) so I need to use the try/catch block so users without a list of groups don't cause early termination.
The JSON data snippet:
{
"people": [
{
"person": {
"name": "joe",
"email": "joe#foo.net",
"groups": [
{
"name": "office",
"id": 23
},
{
"name": "mfg",
"id": 93
} ]
},
"person": {
"name": "bill",
"email": "bill#foo.net",
"groups": [
{
"name": "acctg",
"id": 133
},
{
"name": "mgr",
"id": 207
} ]
}
}
]
}
This is my code so far:
jdata = json.loads...
for person in jdata['people']:
for key, val in person.iteritems():
print "key ", key , " is ", val
print val["name"]
print val["email"]
try:
for gkey, gval in val["groups"][0].iteritems():
print "gval: " + gval
except:
foo=1
Notice I can print out a list of the 0th item in the group list by doing the for gkey...val["groups"][0].iteritems() but what I really want is iterate over all the group lists of each person entry (some people belong to two groups, others 10 or more) so there is no fixed length. How can I do this?
Is that what you want? :
>>> for group in j['people'][0]['person']['groups']:
for k,v in group.items():
print(k,v)
name acctg
id 133
name mgr
id 207
Or more generally:
>>> for person in j['people']:
for group in person['person']['groups']:
print('Name : {} --- ID: {}'.format(group['name'], group['id']))
Name : acctg --- ID: 133
Name : mgr --- ID: 207