I want to get all 'name' from this json and separate by comma
{
"example": [
{
"id": 1,
"name": "blah"
},
{
"id": 2,
"name": "nah"
},
{
"id": 5,
"name": "krah",
},
{
"id": 10,
"name": "ugh"
}
],
}
when im trying to:
example = r_json['example']['name']
print(example)
it returns me:
example = r_json['example']['name']
TypeError: list indices must be integers or slices, not str
output i want is something like:
blah, nah, krah, ugh
The value in "example" is a list. To access items you need to use an index. e.g.
>>> r_json["example"][0]["name"]
'blah'
If you want to get all of the names, you need to loop through each item in the list.
>>> for i in range(len(r_json["example"])):
... print(r_json["example"][i]["name"])
blah
nah
krah
ugh
A simpler way to do this would be to directly iterate over the list and not use an index:
>>> for example in r_json["example"]:
... print(example["name"])
blah
nah
krah
ugh
To put them in a list you can do:
>>> names = []
>>> for example in r_json["example"]:
... names.append(example["name"])
>>> names
['blah', 'nah', 'krah', 'ugh']
An even easier way is to use a comprehension:
>>> names = [example["name"] for example in r_json["example"]]
>>> names
['blah', 'nah', 'krah', 'ugh']
Once you have the names you can use str.join to make your final result:
>>> ", ".join(names)
'blah, nah, krah, ugh'
As a one liner just for fun:
>>> ", ".join(example["name"] for example in r_json["example"])
An even more fun one-liner!
>>> from operator import itemgetter
>>> ", ".join(map(itemgetter("name"), r_json["example"]))
'blah, nah, krah, ugh'
Just as the error says, the value under r_json['example'] is a list of dictionaries, so you can't access it like: r_json['example']['name']. One way to get the names is to use a list comprehension:
example = [d['name'] for d in r_json['example']]
print(*example)
Output:
blah nah krah ugh
Related
I have a nested lists and dictionary's inside a list.
confused how to access the 'Product_Name' inside nested dict
list_1 = [{"group_details":[{"data":[{"product_details":[{"Product":"xyz","Invoice_No":"852","Product_Name":"abc"}]}]}]
To retrieve the indicated value, you must provide the name of each layer and define the index (which in this case are all [0]) needed to analyze each of the containers:
list_1 = [
{
"group_details":[
{
"data":[
{
"product_details":[
{
"Product":"xyz",
"Invoice_No":"852",
"Product_Name":"abc"
}
]
}
]
}
]
}
]
Product_Name = list_1[0]["group_details"][0]["data"][0]["product_details"][0]["Product_Name"]
print(Product_Name)
Result:
abc
Additional request to find via looping:
for containers in list_1:
for group_details in containers["group_details"]:
for data in group_details["data"]:
for product_details in data["product_details"]:
print(product_details["Product_Name"])
Result:
abc
To parse the structure, indent it:
list_1 = [
{"group_details":[
{"data":[
{"product_details":[
{"Product":"xyz", "Invoice_No":"852", "Product_Name":"abc"}]}]}]}]
print(list_1[0]["group_details"][0]["data"][0]["product_details"][0]["Product_Name"])
# abc
list_1 = [{"group_details":[{"data":[{"product_details":[{"Product":"xyz","Invoice_No":"852","Product_Name":"abc"}]}]}]}]
print(list_1[0]["group_details"][0]["data"][0]["product_details"][0]["Product_Name"])
RESULT:
abc
To do this iteratively:
for i in list_1:
for j in i["group_details"]:
for k in j["data"]:
for l in k["product_details"]:
for kk,vv in l.items():
if kk == "Product_Name":
print(vv)
You can use the following nested for loop:
list_1 = [{"group_details":[{"data":[{"product_details":[{"Product":"xyz","Invoice_No":"852","Product_Name":"abc"}] }]}]}]
for item in list_1:
for group_details in item.get('group_details'):
for data in group_details.get('data'):
for product_details in data.get('product_details'):
print(product_details.get('Product_Name'))
I have a list in the below format.
['111: {"id":"de80ca97","data":"test"}', '222: {"id":"8916a167","data":"touch"}', '333: {"id":"12966e98","data":"tap"}']
I need to remove the data column from above list / json and replace it with key value of the list.
I need to transform it to the below structure.
Desired output:
[
{
"score":111,
"id":"de80ca97"
},
{
"score":222,
"id":"8916a167"
},
{
"score":333,
"id":"12966e98"
}
]
Any suggestions or ideas most welcome.
You can use a for loop or you can also use a list comprehension as follows:
>>> import json
>>> l = ['111: {"id":"de80ca97","data":"test"}', '222: {"id":"8916a167","data":"touch"}', '333: {"id":"12966e98","data":"tap"}']
>>> [{'score': int(e.split()[0][:-1]), 'id': json.loads(e.split()[1])['id']} for e in l]
If you prefer to use a for loop:
new_l = []
for e in l:
key, json_str = e.split()
new_l.append({'score': int(key[:-1]), 'id': json.loads(json_str)['id']})
Trying to convert a list of values to be used to find a particular key value in a Dictionary.
I am not able to figure out a pythonic way to do it.
Tried converting the list to string and pass as a key to the dictionary, but it is now working as the list contains integer values also.
l = ['tsGroups', 0, 'testCases', 0, 'parameters', 'GnbControlAddr', 'ip']
d={
"tsGroups": [{"tsId": 19,
"testCases": [{"name": "abcd",
"type": "xyz",
"parameters": {"GnbControlAddr":
{"ip": "192.1.1.1",
"mac": "",
"mtu": 1500,
"phy": "eth2",
}
}
}]
}]
}
print(d["tsGroups"][0]["testCases"][0]["parameters"]["GnbControlAddr"]
["ip"])
Need to convert input list 'l' to a format to be used as
d["tsGroups"][0]["testCases"][0]["parameters"]["GnbControlAddr"]["ip"]
In [5]: d={
...: "tsGroups": [{"tsId": 19,"testCases": [{"name": "abcd","type": "xyz",
...: "parameters": {"GnbControlAddr": {
...: "ip": "192.1.1.1",
...: "mac": "",
...: "mtu": 1500,
...: "phy": "eth2",
...: }
...: }}]}]}
In [6]: L = ['tsGroups', 0, 'testCases', 0, 'parameters', 'GnbControlAddr', 'ip']
In [7]: functools.reduce?
Docstring:
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
Type: builtin_function_or_method
In [8]: t = d
In [9]: for e in L: t = t[e]
In [10]: t
Out[10]: '192.1.1.1'
Can't speak to how pythonic this is, but looping through the list and updating a reference to a new data structure appears to work:
current = d
for key in l:
current = current[key]
print current
Question about appropriate data structure:
I have five variables that will have different values
string based on whether they are in US/Alaska and
at half/full resolution.
So I'm building a 5/2/2 (array or list or dict).
I want to access it with x = DStr(var,'AK','H') , e.g..
For Alaska/half-res, what values for OSP/UL/LR/etc, the variables?
This is a static table, values won't change.
There is no obvious ordering to demand 0,1,2 for indices
Problem is, array doesn't like the string indices and
dict wants one key only, not three.
Any ideas?
You can use tuples to index a dict:
>>> values = {
... ("AK", "H"): ("some", "sample", "data", "to", "return"),
... ("AK", "F"): ("more", "sample", "data", "for", "you"),
... # More data here
... }
>>> a, b, c, d, e = values[("AK", "H")]
>>> a
"some"
Or you can use a nest of dicts:
>>> values = {
... "AK": {
... "H": ("some", "sample", "data", "to", "return"),
... "F": ("more", "sample", "data", "for", "you")
... },
... # Other nested dicts here
... }
>>> a, b, c, d, e = values["AK"]["H"]
>>> a
"some"
If you have a class structure for defining the 5 data points as a part of a single object (which would be a good idea to keep the data grouped together if it is related), you can store instances of the class instead of the tuples:
>>> values = {
... ("AK", "H"): MyClass("some", "sample", "data", "to", "return"),
... ("AK", "F"): MyClass("more", "sample", "data", "for", "you"),
... # More data here
... }
>>> obj = values[("AK", "H")]
>>> obj.osp
"some"
or
>>> values = {
... "AK": {
... "H": MyClass("some", "sample", "data", "to", "return"),
... "F": MyClass("more", "sample", "data", "for", "you")
... },
... # Other nested dicts here
... }
>>> obj = values["AK"]["H"]
>>> obj.osp
"some"
Bear in mind that your question is rather unclear. I really don't understand the meaning of the data you want to model, and I don't know how it will be used.
That being said, a class is a good way to define your own data structures. In this case I guess you have OSP, UL, LR, and "etc". So I would define a class for that:
class MyData:
def __init__(self, osp, ul, lr, etc):
self.osp = osp
self.ul = ul
self.lr = lr
self.etc = etc
Then make your lookup table containing instances of the class:
table = {
'AK': {'H': MyData(1,5,20,'something'),
'F': MyData(3,2,28,'spam') },
'FL': {'H': MyData(42,5,20,'eggs'),
'F': MyData(2,13,7,'ham') },
}
Then I can define a function matching the signature you showed in your question. I ignore the argument var because your question doesn't tell me anything about it.
def DStr(var, state, resolution):
return table[state][resolution]
If you have fixed length two strings that will make up a lookup, you can concatenate them together. Might be simpler than having a dict of dict of values. Values can be in a list.
table = {'AKH': [1,"two",3.14],
'AKF': [2,"four", 6.28]
}
state = 'AK'
res = 'F'
table[state+res]
output
[2, 'four', 6.28]
I have a dictionary like:
Data = {
"weight_factors" : {
"parameter1" : 10,
"parameter2" : 30,
"parameter3" : 30
},
"other_info" : {
}
}
I want to get the sum of all values that are under the key "weight_factors":
sum = Data["weight_factors"]["parameter1"] +
Data["weight_factors"]["parameter2"] +
Data["weight_factors"]["parameter3"]
Currently, in order to avoid entering Data["weight_factors"] repeatedly, I use the following commands:
d = Data["weight_factors"]
d["parameter1"] + d["parameter2"] + d["parameter3"]
But, I guess there should be an operator that does the same thing, without storing Data["weight_factors"] as an intermediate variable. I was wondering if such a command or an operator exists.
Data["weight_factors"]<unknown operator>(["parameter1"] +
["parameter2"] +
...
["parametern"])<unknown operator>
EDIT:
In the example given above, it was just a sum operation. But it could for example be:
Data["weight_factors"]["parameter1"] * Data["weight_factors"]["parameter2"] + Data["weight_factors"]["parameter3"]
But I do not want enter Data["weight_factors"] repeatedly. That's the thing I am searching for... I don't know whether such an operator exists. (In MATLAB, there exists such a thing for cell structures).
No, that kind of operator does not exist for the built-in dict type.
I suppose you could make your own dict type that inherited from dict and overloaded an operator:
class MyDict(dict):
def __add__(self, other):
"""Overload the + operator."""
...
but that is somewhat inefficient and not very good for readability.
If you just want to sum the values, you can use sum and dict.values (dict.itervalues if you are using Python 2.x):
>>> Data = {
... "weight_factors" : {
... "parameter1" : 10,
... "parameter2" : 30,
... "parameter3" : 30
... },
... "other_info" : {
... }
... }
>>> sum(Data["weight_factors"].values())
70
>>>
Otherwise, I would just use what you have now:
d = Data["weight_factors"]
myvar = d["parameter1"] * d["parameter2"] + d["parameter3"]
It is about as clean and efficient as you can get.
For a general solution to repeatedly get the same item from a mapping or index, I suggest the operator module's itemgetter:
>>> import operator
>>> Data = {
"weight_factors" : {
"parameter1" : 10,
"parameter2" : 30,
"parameter3" : 30
},
"other_info" : {
}
}
Now create our easy getter:
>>> get = operator.itemgetter('weight_factors')
And call it on the object whenever you want your sub-dict:
>>> get(Data)['parameter1']
returns:
10
and
>>> sum(get(Data).values())
returns
70
If this is just "how do I access a dict's values easily and repeatedly?" you should just assign them like this, and you can reuse them again and again.
In Python 2:
vals = Data['weight_factors'].values()
In Python 3, values returns an iterator, which you can't reuse, so materialize it in a list:
vals = list(Data['weight_factors'].values())
and then you can do whatever you want with it:
sum(vals)
max(vals)
min(vals)
etc...