Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have this dictionary but I'm not able to print it, could anyone tell me if there is an error?
groseries = {
'fruits':[{
'apples':['7'],
'bananas':['4'],
'lemmons':['7']
}],
'vegestables':[{
'tomatoes':['3'],
'carrots':['9'],
'onions':['6']
}],
'cereals':[{
'wheat':['11'],
'granola':['7'],
'kornflakes':['9']
}]
}
print (groseries['cereals'][2])
groseries['cereals'] has only one element. So using index 2 for it throws the IndexError exception.
Thus the right usage is with the index 0 and the key 'kornflakes':
print(groseries['cereals'][0]['kornflakes'])
Perhaps you meant to format your code like this?:
groceries = {
'fruits': {
'apples':7,
'bananas':4,
'lemons':7
},
'vegetables': {
'tomatoes':3,
'carrots':9,
'onions':6
},
'cereals': {
'wheat':11,
'granola':7,
'cornflakes':9
}
}
So then you can print how many apples you have like this:
print (groceries['fruits']['apples'])
or for cornflakes:
print (groceries['cereals']['cornflakes'])
On a trivial note, shouldn't tomatoes be in fruit? :P
You need groseries['cereals'][0]['kornflakes'].
It's a list of dictionaries (containing only one dictionary) inside groseries['cereals'].
Change your groseries dictionary to
groseries = {
'fruits': {
'apples': 7,
'bananas': 4,
'lemmons': 7
},
'vegestables': {
'tomatoes': 3,
'carrots': 9,
'onions': 6
},
'cereals': {
'wheat': 11,
'granola': 7,
'kornflakes': 9
}
}
(no lists - as all your lists have just 1 item - no numbers in apostrophes, PEP 8 Style Guide's formatting) - and your life will be much easier.
And yes, then you may print the number (or the price?) of your favorite kornflakes cereal as simple as
print(groseries['cereals']['kornflakes'])
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
Improve this question
I am new to boto3 and am successfully getting the AWS info I want when using print, but I cannot for some reason append to a list. I can print out and get exactly what I want, but I cannot for the life of me get out into a list. I tried to make an empty dict and update that empty dict which would be preferable but it didn't work either. Got None.
It returns None when trying to add to a list, but wrks perfectly with print().
def vol_snapshots_size(**kwargs):
session = boto3.Session(profile_name='snap')
ec2 = session.client('ec2', region_name=kwargs['region'])
ebs = session.client('ebs', region_name=kwargs['region'])
snapshots = ec2.describe_snapshots(
Filters=[
{
'Name': 'volume-id',
'Values': [
kwargs['volume_id'],
]
}
],
OwnerIds=['self']
)
sorted_snapshots = sorted(snapshots['Snapshots'], key=lambda snap: snap['StartTime'], reverse=True)
snap_list = []
for i in range(len(sorted_snapshots)-1):
snap = sorted_snapshots[i]
diff_size = snapshots_size(ebs, sorted_snapshots[i]["SnapshotId"], sorted_snapshots[i+1]["SnapshotId"])
out = {'date': snap["StartTime"], 'id': snap["SnapshotId"], 'VolumeID': kwargs['volume_id'], 'size': format_bytes(diff_size)}
snap_list.append(out)
return snap_list
EDIT
This works and prints the data. So it is weird I cannot return.
sorted_snapshots = sorted(snapshots['Snapshots'], key=lambda snap: snap['StartTime'], reverse=True)
out = []
for i in range(len(sorted_snapshots)-1):
snap = sorted_snapshots[i]
diff_size = snapshots_size(ebs, sorted_snapshots[i]["SnapshotId"], sorted_snapshots[i+1]["SnapshotId"])
out.append({'date': snap["StartTime"], 'id': snap["SnapshotId"], 'VolumeID': kwargs['volume_id'], 'size': format_bytes(diff_size)})
print(out)
Just wrote this rough test function to interact with the function above
def get_snap_sizes():
try:
snap.vol_snapshots_size(
region='us-east-1',
volume_id='OMITTED',
output='text'
)
except Exception:
pass
print(get_snap_sizes()
This question already has answers here:
How do I get the last element of a list?
(25 answers)
Closed 1 year ago.
Here I'm trying to get the last m2id to print it into console.
[{
"m2id":"865199733949071370",
"author":{
"id":"862323352869797948"
}
},
{
"m2id":"865199658103078925",
"author":{
"id":"751742911682445312"
}
}]
And here's the code I wrote for it. (r.json being the json above):
data = r.json()
for id in data:
id3 = id["id"][-1]
print(id3)
Running the code gave me the last number of the first m2id, Which is not what I want.
Edit: data[-1]["id"] Worked. Thanks to everyone!
You can try this
x = [{
"m2id":"865199733949071370",
"author":{
"id":"862323352869797948"
}
},
{
"m2id":"865199658103078925",
"author":{
"id":"751742911682445312"
}
}]
print(x[len(x)-1]["m2id"])
Output
865199658103078925
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
[{
data: "31/05/2010 19:39:00",
empresa: {
codigo: 1
},
descricao: "teste",
tipoEvento: "RHYTHM VARIATION"
},
{
data: "31/05/2010 18:15:00",
empresa: {
codigo: 1
},
descricao: "teste ",
tipoEvento: "RHYTHM VARIATION"
}]
This is an overly simple question, and I would encourage you to read the documentation in the future, but nonetheless:
import json
your_str_data = r'''
[{"data":"31/05/2010 19:39:00","empresa":{"codigo":1},"descricao":"teste","tipoEvento":"RHYTHM VARIATION"},{"data":"31/05/2010 18:15:00","empresa":{"codigo":1},"descricao":"teste ","tipoEvento":"RHYTHM VARIATION"}]
'''
jdata = json.loads(your_str_data)
import pprint
pprint.pprint(jdata)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have this JSON array with multiple roots:
[
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "sub.test.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
},
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]
I want to iterate over it and print issuer_name values in Python. Any solution, please?
Use the json package and load the json. Assuming it is a string in memory (as opposed to a .json file):
jsonstring = """
[
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "sub.test.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
},
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]"""
import json
j = json.loads(jsonstring)
[item["issuer_name"] for item in j]
Gives:
["C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
'C=US, O=Amazon, OU=Server CA 1B, CN=Amazon']
Now, these don't look like names to me, but that's what is assigned to the issuer_name field, so I think that's something you have to take up with the owner of the data.
If it's a file, you do the loading in this basic pattern:
# something like this
with open("jsonfile.json", "rb") as fp:
j = json.load(fp)
See the docs here: https://docs.python.org/3.7/library/json.html
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
how parse multi-level json data, in Mongodb with Python 3.5?
PLAYER_DEFAULT = {
"_id": Inc(PlayersDB),
"mail": "test#gmail.com",
"password": "123456",
"token": uuid4().hex,
"username": "applet",
"user_info":
{
"show_name" : "Hero",
"rate_us": 20000,
"rating": 300,
"gcg": "",
"ration":0,
"items":
[
{"id":1, "item_type":"socket", "name":"aEveA", "data":{"level":1, "stat":"AVA"}},
{"id":2, "item_type":"socket", "name":"aEveA", "data":{"level":4, "stat":"AVA"}},
{"id":3, "item_type":"socket", "name":"Hestos", "data":{"level":9, "stat":"Hest"}},
{"id":4, "item_type":"user", "name":"AAACZX", "data":{"expr":1000}},
{"id":5, "item_type":"user", "name":"AAAAZZZCX", "data": {"expr":1000}}
]
}
}
how get data level and stat in items?
["_id"]->["show_name"]
["_id"]->["user_info"]->["items"]
["_id"]->["user_info"]->["items"] -> get value by "stat" in items[0]
me need get items id, by items "stat" value
i use loop
how get x count?
for x in PlayersDB.find({"_id":1}):
print(x["user_info"]["items"][x.count()])
And... how to update "item_type", by "id", in "items"?
And how to delete 1 docuement by "id":1 in "items"?
For that document, try:
doc['user_info']['items'][0]['data']['stat']
If you have a doc for a player, and want to count how many items that player has, you will use some built-in Python function, which I will call XXX, and which you should research to see what that function is, and use it on the items attribute of the doc:
number_of_items = XXX(doc['user_info']['items'])
And in future, please use the same names and structure in your question as in your posted examples.