I cannot get values inside my python dictionairy, created from a json file, to print at all. Here is my JSON:
{
"Questions": [
{
"Q1":"What is capital of egypt?",
"T":"London",
"2":"France",
"3":"Egypt"
},
{
"Q2":"What is capital of USA?",
"T":"London",
"2":"France",
"3":"Egypt"
}
]
}
And here is my python:
import json
with open("questions.json") as f:
data = json.load(f)
print(data["Questions"]["Q1"])
This returns the error: list indices must be integers or slices, not str
What am I doing wrong? I have checked the syntax for printing and it all seems correct.
A good strategy is to start by removing code until it works. For example, instead of
print(data["Questions"]["Q1"])`
You should try
print(data["Questions"])`
The output from this is
[{'Q1': 'What is capital of egypt?', 'T': 'London', '2': 'France', '3': 'Egypt'},
{'Q2': 'What is capital of USA?', 'T': 'London', '2': 'France', '3': 'Egypt'}]
From there, you can try to index like you were doing in the question:
[{'Q1': 'What is capital of egypt?', 'T': 'London', '2': 'France', '3': 'Egypt'},
{'Q2': 'What is capital of USA?', 'T': 'London', '2': 'France', '3': 'Egypt'}]['Q1']
Except that doesn't make sense, because you're trying to index a list, and indexes in a list are ints, not strings.
So to get the result you're expecting, you should use data["Questions"][0] to index the first question.
A better solution, in my opinion, is to change the structure of the JSON to something that makes a little more sense. This is how I would do it:
{
"Questions": {
"Q1": {
"Q":"What is capital of egypt?",
"T":"London",
"2":"France",
"3":"Egypt"
},
"Q2" : {
"Q":"What is capital of USA?",
"T":"London",
"2":"France",
"3":"Egypt"
}
}
}
Now you can perform a lookup with Q1 or Q2 just like you expect.
The value of Questions is a list. Like the error says, the index must be an integer.
The first question is going to be data["Questions"][0], the second is data["Questions"][1] and so on.
If you want the value of "Q1" for the first question, you need to use data["Questions"][0]["Q1"]
Try this piece of code:
import json
with open("questions.json") as f:
data = json.load(f)
print(data["Questions"][0]["Q1"], data["Questions"][1]["Q1"])
Related
input=
list1=[{'Name':'Jack','email':'xyz#foo.com'},
{'Name':'Sam','email':'sam#xyz.com'},
{'Name':'Dan','email':'dan#xyz.com'}]
Required output =
list1=[{"Name":"Jac","email":"xyz#foo.com"},
{"Name":"Sam","email":"sam#xyz.com"},
{"Name":"Dan","email":"dan#xyz.com"}]
How to get this as output? I've tried
list2=[]
for items in response:
list2.append(json.dumps(items))
output I'm getting is
['{'Name':'Jack','email':'xyz#foo.com'}',
'{'Name':'Sam','email':'sam#xyz.com'}',
'{'Name':'Dan','email':'dan#xyz.com'}']
Please use json.dumps like this:
import json
list1=[{'Name':'Jack','email':'xyz#foo.com'},
{'Name':'Sam','email':'sam#xyz.com'},
{'Name':'Dan','email':'dan#xyz.com'}]
print(list1)
list2 = json.dumps(list1)
print(list2)
#[{'Name': 'Jack', 'email': 'xyz#foo.com'}, {'Name': 'Sam', 'email': 'sam#xyz.com'}, {'Name': 'Dan', 'email': 'dan#xyz.com'}]
#[{"Name": "Jack", "email": "xyz#foo.com"}, {"Name": "Sam", "email": "sam#xyz.com"}, {"Name": "Dan", "email": "dan#xyz.com"}]
Generally, you want to do json.dumps() on the whole data structure, not on individual pieces.
It's not clear from your question what form the input is; is it a data structure in a file, or in memory?
If it's in a file, the first step will be reading it, so it's in memory, and so each part has the right form.
Once that's done, you can do json.dumps() on the whole list.
#I have these two lists and i want to convert these lists such that it shows the following output :
l=['SDL-A-19.0.0-1-WX-ExP.tar','SDL-B-19.0.0-1-WX-ExP.tar','SDL-C-19.0.0-1-WX-ExP.tar','ReadMe']
s=['version','name']
#required output :
{"version": "19.0.0-1", "name": "A"}, {"version": "19.0.0-1", "name": "B"},
{"version": "19.0.0-1", "name": "C"}
Kindly suggest some solutions
You probably need a regex to match the different names those files can take. Based on the example you've provided, you could probably do something along the lines of:
import re
out = []
for s in l:
try:
pat = r'^[A-Z]{3}-(?P<name>[A-Z])-(?P<version>(?:\d+\.){2}\d+-\d+).*?'
match= re.search(pat, s)
out.append({'version':match.group('version'), 'name':match.group('name')})
except AttributeError:
pass
print(out)
[{'vesion': '19.0.0-1', 'name': 'A'}, {'vesion': '19.0.0-1', 'name': 'B'},
{'vesion': '19.0.0-1', 'name': 'C'}]
Though you might need to tweak it a little depending on the actual file names you might have. See the regex demo for the above cases.
You can try the below but this has the following assumptions.
The last element of l is always "Readme" and should be ignored.
The positions of the version and name in l are consistent.
b=[]
for i in range(len(l)-1):
a ={}
a[s[0]] = l[i][6:14]
a[s[1]] = l[i][4]
b.append(a)
# b is your final list of dictionaries
print(b)
file1.py
a = {'fullname':'John Wick', 'Age': 35 , 'job':'Hitman'}
b = {'fullname':'Mark Zuckerberg', 'Age': 30, 'job': 'Developer'}
c = {'fullname':'Will smith', 'Age': 45, 'job': 'Actor'}
d = {'fullname':'Messi' , 'Age': 28, 'job' : 'Player'}
so on... and many more details
Notice : the dict variables are very different.
Task is to obtain "Age" from user input like "Name" or "Job"
for ex: user enters messi... he must get 28 as the output.
File2.py
from File1.py import *
#what should the code be to access the age
user_input=raw_input("enter a Name: ")
# user_input contains the name of the person I want to get the Age
I have tried using globals() but it complicates my situation
It creates a List, which then has to be accessed by integer.
Is there any way to search the values inside the dict and match with IF condition ??
Yes, there are ways to do this, but you're complicating the situation.
First of all, simplify your program even more: pull the remote code into your program file, and solve the access problem there. After that works, then you split it into a second file.
Second, if you want those items to be in a form you can easily search, do that. At the moment, you went out of your way to separate them into distinct variables, when you obviously want to keep them together. Do this in one of two ways:
(1) simple list:
people = [
{'fullname':'John Wick', 'Age': 35 , 'job':'Hitman'},
{'fullname':'Mark Zuckerberg', 'Age': 30, 'job': 'Developer'},
{'fullname':'Will smith', 'Age': 45, 'job': 'Actor'},
{'fullname':'Messi' , 'Age': 28, 'job' : 'Player'}
]
Now, use your normal list search methods to find the matching item.
(2) Dictionary, indexed the way you want to use it:
people = {
'John Wick': {'Age': 35 , 'job':'Hitman'},
'Mark Zuckerberg': {'Age': 30, 'job': 'Developer'},
'Will smith': {'Age': 45, 'job': 'Actor'},
'Messi': {'Age': 28, 'job' : 'Player'}
}
This way, you get the person's record with a direct reference, people[user_input].
Does that get you moving?
try to create a backup of your file1.py as file1.txt and do operations on that very file
sharing a small usefull snippet here
import re
user_input=raw_input("enter a Name: ")
with open("file1.txt") as f:
for line in f:
#print line
matches = re.findall(r'\'(.+?)\'', line)
if user_input in matches:
age = re.findall(r'\d+', line)
print age
I'm accessing a third-party API that returns a dictionary that contains both simple values and nested (embedded?) dictionaries. I need to convert this to a CSV file, but I need help extracting and exporting specific values from the nested dictionaries.
Here's a simplified example of what I'm getting back:
accounts = {
'Id': '0131232',
'AccountName': 'CompanyX',
'Active': False,
'LastModifiedBy': {'type': 'User', 'Id': '', 'Name': 'Joe Smith'}
},
{
'Id': '987654',
'AccountName': 'CompanyY',
'Active': True,
'LastModifiedBy': {'type': 'User', 'Id': '', 'Name': 'Mary Johnson'}
}
I'm trying to export this to a CSV file with the following code:
with open('output.csv', 'w') as f:
dwriter = csv.DictWriter(f, accounts[0].keys())
dwriter.writeheader()
dwriter.writerows(accounts)
f.close()
What I want in the CSV file is the following:
Id,AccountName,Active,LastModifiedBy
0131232,CompanyX,False,Joe Smith
987654,CompanyY,True,Mary Johnson
What I'm getting with my code above is the following:
Id,AccountName,Active,LastModifiedBy
0131232,CompanyX,False,"{'type': 'User', 'Id': '', 'Name': 'Joe Smith'}"
987654,CompanyY,True,"{'type': 'User', 'Id': '', 'Name': 'Mary Johnson'}"
Obviously I need to extract the key-value pair I want from the nested dictionary and assign that value to the higher-level dictionary. My question is how do I do that while still handling the simple values as is?
It seems like this could be done with dictionary comprehension, but I'm not sure I can do a conditional with that.
Alternatively I could go through each record, check each value to see if it's a dictionary, and write out the values I want to a new dictionary, but that feels a little too heavy.
Full disclosure: I'm new to Python, so apologies if I'm missing something obvious.
Thanks!
- Chris
If you don't need accounts for anything else you can do:
for account in accounts:
account['LastModifiedBy'] = account['LastModifiedBy']['Name']
otherwise, .copy() it and do the same.
So I am working a dictionary with some nice information, and I wan to print out the words in a nicely formatted way by means of another function.
I have this:
norwDict = {
'et hus': {
'pron': 'hUs',
'def': 'house',
'POS': 'noun',
'gen': 'neuter', }
'en blomst' :{
'pron':'blOMst',
'def':'flower',
'POS': 'noun',
'gen':'masc', }
I want to print this so that it looks like:
printWord(norwDict, 'blomst')
en blomst (blOmst), noun
a flower.
What things do I do in order to format it like that in the function def printWord()?
I'd use str.format. See: https://docs.python.org/2/library/string.html#formatstrings
As it is, it would work something like this:
def print_word(your_dict, your_word):
# you need some sort of logic to go from 'blomst' to 'en blomst'
key, = {k for k in your_dict.keys() if your_word in k}
# {'pron': 'blOMSt', ... }
values = your_dict[key]
print """{key} ({pron}), {POS}
a {def}""".format(key=key, **values)
str.format lets you pass in named arguments, which you can easily get here by doing ** unpacking on your inner dict.