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
Related
Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary
reda.json file
[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
import json
import collections
json_data = json.load(open('reda.json'))
if type(json_data) is dict:
json_data = [json_data]
d = collections.OrderedDict((json_data))
h = tuple(d.keys()).index('break')
print(h)
Also tried this
j = 'break'
for i in json_data:
if j in i:
print(j.index('break'))
Result is 0
``
You can use enumerate to generate indices for a sequence:
json_data = [{"carl": "33"}, {"break": "55"}, {"user": "heake"}]
key = 'break'
for index, record in enumerate(json_data):
if key in record:
print(index)
This outputs: 1
You don't require collections for this. Simply use list comprehension to generate a list and then get the index.
Here's my code:
import json
json_data = json.load(open('reda.json'))
json_key_index = [key for key in json_data]
print(json_key_index.index("break"))
Also, looking at your reda.json the format doesn't seem pretty well-versed. I recommend changing the reda.json to:
{
"carl": "33",
"break": "55",
"user": "heake"
}
I have a list of dictionaries as a key value pairs, where I want to access the data of each dict by key:
sample data:
['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"',...
real data
>>> data
['"imageUrl":"/images/products/klein/04047122_k.jpg"', '"art":"04047122"', '"productId":"170336"'; } } }) ']
This unfortunatelly does not work:
re.findall(r'(?:number\(\{)(.*)', data)[0].split(',')
How can I retrieve the values by name e.g. data['number'] ?
For a more robust solution, since each string in the input list is a valid line of CSV, delimited by a colon, you can use csv.reader to parse the list and then pass the resulting sequence of key-value pairs to the dict constructor to build a dict:
import csv
lst = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
data = dict(csv.reader(lst, delimiter=':'))
You can then access data['number'] as desired.
Try to convert your data to a real dictionary:
data = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
data_dict = dict([x.replace('"','').split(":") for x in data])
and then you will be able to access your keys:
print(data_dict["number"]) # output: 04047122
You can convert your string list to an actual dictionary easily:
>>> ls = ['"imageUrl":"/images/4.jpg"', '"number":"04047122"', '"name":"test"']
>>> data = dict(elem.replace('"', '').split(':') for elem in ls)
>>> data
{'imageUrl': '/images/4.jpg', 'number': '04047122', 'name': 'test'}
>>> data['number']
'04047122'
I must write a dictionary. This is my first time doing it and I can't wrap my head around it. The first 5 element should be the key to it and the rest the value.
for i in verseny:
if i not in eredmeny:
eredmeny[i] = 1
else:
eredmeny[i] += 1
YS869 CCCADCADBCBCCB this is a line from the hw. This YS869 should be the key and this CCCADCADBCBCCB should be the value.
The problem is that I can't store them in a dictionary. I'm grinding gears here but getting nowhere.
Assuming that erdemeny is your dictionary name and that verseny is the list that includes your values and keys strings. This should do it:
verseny = ['YS869 CCCADCADBCBCCB', 'CS769 CCCADCADBCBCCB', 'BS869 CCCADCADBCBCCB']
eredmeny = {}
for i in verseny:
key, value = i.split(' ')[0], i.split(' ')[1]
if key not in eredmeny.keys():
eredmeny[key] = value
else:
eredmeny[key].append(value)
I'm not really understanding the question well, but an easy way to do the task at hand would be converting the list into a string and then using split():
line = 'YS869 CCCADCADBCBCCB'
words = l.split()
d = {ls[0]: ls[1]}
print(d)
this is the basic skill in python. I hope you can refer to the existing materials. As your example, the following demonstrations are given:
line = 'YS869 CCCADCADBCBCCB'
dictionary = {}
dictionary[line[:4]] = line[5:]
print(dictionary) # {'YS86': ' CCCADCADBCBCCB'}
I have a list of dictionaries that is structured as such:
json_data = [{'a':10,'text':"Salam"},{'a':4,'text':"Hello Friend"}]
I have been able to iterate through the list and extract the key 'text' from each dictionary:
json1_text = [[[value] for value in json1_data[index].get('text')] for
index in range(len(json1_data))]
However, the new json1_text list does not contain sentences from returned from the dictionary, but rather each individual letter:
json1_text[0]
Returns:
[['S'],['a'],['l'],['a'],['m']]
How would I be able to return the whole sentence "Hello Friend" as opposed to each individual letter and storing each in a list?
Thanks in advance!
json1_text = [v for i in json_data for k,v in i.items() if isinstance(v,str)]
print (json1_text)
Result:
['Salam', 'Hello Friend']
Below is my requirement. Below is the data that is present in json file:
{"[a]":" text1","[b]":" text2","[a]":" text3","[c]":" text4","[c]":" Text5"}.
The final output should be like
{"[a]":[" text1","text3"],"[b]":" text2","[c]":" text4"," Text5"]}.
I tried below code:
data_in= ["[a]"," text1","[b]"," text2","[a]"," text3","[c]"," text4","[c]"," text5"]
data_pairs = zip(data_in[::2],data_in[1::2])
data_dict = {}
for x in data_pairs:
data_dict.setdefault(x[0],[]).append(x[1])
print data_dict
But the input it takes is more in form of List than a dictionary.
Please advise.
Or is there a way where i can convert my original dictionary into list with multiple values as list will take only unique values. Please let me know the code also i am very new to Python and still learning it. TIA.
Keys are unique within a dictionary while values may not be.
You can try
>>> l = ["[a]"," text1","[b]"," text2","[a]"," text3","[c]"," text4","[c]"," text5"]
>>> dict_data = {}
>>> for i in range(0,len(l),2):
if dict_data.has_key(l[i]):
continue
else:
dict_data[l[i]] = []
>>> for i in range(1,len(l),2):
dict_data[l[i-1]].append(l[i])
>>> print dict_data
{'[c]': [' text4', ' text5'], '[a]': [' text1', ' text3'], '[b]': [' text2']}