I have a Json file with a dictionary that looks like
{"tvs": 92, "sofas": 31, "chairs": 27, "cpus": 007}
I'm trying loop though the dictionary and print the key with its corresponding value, in my code I'm getting a too many values to unpack error.
with open('myfile.json', "r") as myfile:
json_data = json.load(myfile)
for e, v in json_data:
for key, value in e.iteritem():
print key, value
So, by default a dict will iterate over its keys.
for key in json_data:
print key
# tvs, sofas, etc...
Instead, it seems like you want to iterate over the key-value pairs. This can be done by calling .items() on the dictionary.
for key, value in json_data.items():
print key, value
Or you can iterate over just the values by calling .values().
Try this:
with open('myfile.json', "r") as myfile:
json_data = json.load(myfile)
for e, v in json_data.items():
print e,v
You have an extra loop in your code, also, the input file has invalid data 007. Loading it into json should give you an error.
Is this what you're looking for?
>>> json = {"tvs": 92, "sofas": 31, "chairs": 27, "cpus": 007}
>>> for j in json:
... print j, json[j]
...
chairs 27
sofas 31
cpus 7
tvs 92
Related
I am trying to use the json data which is in data_dict and use it in the for loop to segregate the json data into different attributes with the help of k and v. But I got struck with the above AttributeError, any help is much appreciated.
with open('Yelp.json', 'r',encoding= 'utf8') as f:
data_dict = json.load(f)
count = 0
for (k, v) in data_dict.items():
for values in v:
#print()
for key in values:
if str(key) == 'business_id':
lsthrs[str(key)]=values[key]
lstcat[str(key)]=values[key]
lstnbh[str(key)]=values[key]
lstatr[str(key)]=values[key]
lstgoodforatr[str(key)]=values[key]
lstparkingatr[str(key)]=values[key]
lstambienceatr[str(key)]=values[key]
tep = values[key]
Since your JSON file starts with a [ (as mentioned in the question comments), the contents of your file will be loaded (at json.load) as a list of dictionaries:
with open('Yelp.json', 'r',encoding= 'utf8') as f:
data_list = json.load(f) # Since `data_dict` is actually a list
count = 0
# To find the keys of each object, you could use this print:
# print(data_list[0].keys())
for values in data_list: # Remember that `values` is a dict
for key in values: # The keys of the `values` dict
if str(key) == 'business_id':
...
I have the following txt... (I've saved as a dictionary)
"{'03/01/20': ['luiana','macarena']}\n"
"{'03/01/21': ['juana','roberta','mariana']}\n"
"{'03/01/24': ['pedro','jose','mario','luis']}\n"
"{'03/01/24': ['pedro','jose','mario','luis']}\n"
"{'03/01/22': ['emanuel']}\n"
the problem is that I want to open it as a dictionary, but I don't know how I can do it. I've tried with:
f = open ('usuarios.txt','r')
lines=f.readlines()
whip=eval(str(lines))
but it's not working... my idea is for example just take the dictionaries that have as a value the next day 03/01/24
if you want to to have only one dict with all the saved dictionaries you can use:
import ast
my_dict = {}
with open('your_file.txt', 'r') as fp:
for line in fp.readlines():
new_dict = ast.literal_eval(line)
for key, value in new_dict.items():
if key in my_dict:
my_dict[key].extend(value)
else:
my_dict[key] = value
print(my_dict)
output:
{'03/01/20': ['luiana', 'macarena'], '03/01/21': ['juana', 'roberta', 'mariana'], '03/01/24': ['pedro', 'jose', 'mario', 'luis', 'pedro', 'jose', 'mario', 'luis'], '03/01/22': ['emanuel']}
if yo could change the format you are saving the strings from
"{'03/01/20': ['luiana','macarena']}\n"
to
'{"03/01/20": ["luiana","macarena"]}\n'
Then you could just do the following:
import json
line = '{"03/01/20": ["luiana","macarena"]}\n'
d = json.loads('{"03/01/20": ["luiana","macarena"]}\n')
The result would be a dictionary d with dates as keys:
>>> {'03/01/20': ['luiana', 'macarena']}
Them, it would be just a mater of looping over the lines of your file and adding them to your dictionary.
An alternative approach would be to use pickle to save your dictionary instead of the .txt, them use it to load from the disk.
I have a file that has names put together that are related to each other, and I need the first set to a key, the second to a value, but when I run the program, I get the error
ValueError: too many values to unpack
I have researched this, but, I haven't found a way to fix it. Below is the code, and a link to some of the material I found in trying to fix this issue.
http://www.youtube.com/watch?v=p2BwrdjlsW4
dataFile = open("names.dat", 'r')
myDict = {}
for line in dataFile:
k,v = line.strip( ). split(",")
myDict[k.strip (":")] = v.strip ( )
print(k, v)
dataFile.close()
def findFather(myDict, lookUp):
for key, value in myDict.items ( ):
for v in value:
if lookUp in value:
return key
lookUp = raw_input ("Enter a son's name: ")
print "The father you are looking for is ",findFather(myDict, lookUp)
the file is saved as "names.dat" and is listed all on one line with the values:
john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos
The code
line.strip( ). split(",")
returns a list like:
["jhon:fred", "fred:bill", "sam:tony", ...]
so, when you do
k,v = line.strip( ). split(",")
you're trying to put all values of that list into k and v that are only two.
Try this code:
for line in dataFile:
for pair in line.strip(). split(","):
k,v = pair. split(":")
myDict[k.strip (":")] = v.strip()
print(k, v)
NOTE: The code above is just for remove the error you're getting. I do not guarantee that this code is going to do what you want to do. Also I've not idea about what are you trygin to du with the code:
myDict[k.strip (":")] = v.strip()
I got this code for implementing my needing:
import json
json_data = []
with open("trendingtopics.json") as json_file:
json_data = json.load(json_file)
for category in json_data:
print category
for trendingtopic in category:
print trendingtopic
And this is my json file:
{
"General": ["EPN","Peña Nieto", "México","PresidenciaMX"],
"Acciones politicas": ["Reforma Fiscal", "Reforma Energética"]
}
However I'm getting this printed:
Acciones politicas
A
c
c
i
o
n
e
s
p
o
l
i
t
i
c
a
s
General
G
e
n
e
r
a
l
I want to get a dictionary being Strings the keys and got a list as value. Then iterate over it. How can I accomplish it?
json_data is a dictionary. In your first loop, you're iterating over a list of the dictionary's keys:
for category in json_data:
category will contain key strings - General and Acciones politicas.
You need to replace this loop, which iterates over keys' letters:
for trendingtopic in category:
with the below, so that it iterates over the dictionary elements:
for trendingtopic in json_data[category]:
I'd use the .iteritems() method of the dictionary which returns key/value pairs:
for category, trending in json_data.iteritems():
print category
for topic in trending:
print topic
These are the contents of my text file (eg:abc.doc):
{'data': [{'name': 'abc'},{'name': 'xyz'}]}
After opening the file in python; how do i remove all the brackets, quotes and commas.
The final output should be:
data:
name:abc
name:xyz
Use ast.literal_eval() to turn it into a python structure, then print the values:
with open(r'd:\output1.doc', 'r') as inputfile:
inputstring = inputfile.read()
data = ast.literal_eval(inputstring)
for key, sublist in data.items():
print '{}:'.format(key)
for subdict in sublist:
for key, value in subdict.items():
print('{}:{}'.format(key, value))
For your example that results in:
>>> inputstring = "{'data': [{'name': 'abc'},{'name': 'xyz'}]}"
>>> import ast
>>> data = ast.literal_eval(inputstring)
>>> for key, sublist in data.items():
... print '{}:'.format(key)
... for subdict in sublist:
... for key, value in subdict.items():
... print '{}:{}'.format(key, value)
...
data:
name:abc
name:xyz
However: If you got this from the Facebook API, then you transcribed the format incorrectly. The Facebook API gives you JSON data, which uses double quotes (") instead:
{"data": [{"name": "abc"},{"name": "xyz"}]}
in which case you should use the json library that comes with Python:
import json
data = json.loads(inputstring)
# process the same way as above.
If you have a filename, you can ask the library to read straight from the file using:
data = json.load(filename) # note, no `s` after `load`.
Looks to me like you have json, which can be easily parsed using pyjson:
import json
obj=json.loads(u'''{'data': [{'name': 'abc'},{'name': 'xyz'}]}''')
Bob's your uncle now, innit?