0

I wanted to read tar.json file, so I write:

import json
with open('tar.json', "r", encoding='utf-8') as read_file:
          data = json.load(read_file) 

and print it as dictionary, for which the key will be "linia" (written as int) and the value will be value tuple.

For example, for "linia 52" I want to get data in format:

{52: ('Czerwone Maki P+R', 'Chmieleniec', 'Kampus UJ', 'Ruczaj', 'Norymberska', 'Grota-Roweckiego', 'Lipińskiego', 'Kobierzyńska', 'Słomiana', 'Kapelanka', 'Szwedzka', 'Rondo Grunwaldzkie', 'Orzeszkowej', 'Stradom', 'Starowiślna', 'Poczta Główna', 'Teatr Słowackiego', 'Lubicz', 'Rondo Mogilskie', 'Cystersów', 'Białucha', 'TAURON Arena Kraków Wieczysta', 'Muzeum Lotnictwa', 'AWF', 'Stella-Sawickiego', 'Czyżyny', 'Rondo Czyżyńskie', 'Os. Kolorowe', 'Plac Centralny im. R.Reagana', 'Os. Zgody', 'Rondo Kocmyrzowskie im. Ks. Gorzelanego', 'DH Wanda', 'Rondo Hipokratesa', 'Dunikowskiego', 'Kleeberga', 'Piasta Kołodzieja')}

How to do this? And how to find for every key number of values tuples?

I know that command: >>> data["linia"][19]["przystanek"][1]["name"]

returns

'Chmieleniec 02'
1
  • What have you tried so far? It looks like the value of key linia is a list of dictionaries. You probably want to iterate over those entries, formatting them as appropriate. "Iterate" means "you need a loop of some sort".
    – larsks
    Commented Oct 22, 2022 at 1:14

1 Answer 1

0

This should give you what you need.

import json
with open('tar.json', "r", encoding='utf-8') as read_file:
          data = json.load(read_file) 
          out = dict()
          for item in data['linia']:
            keys = list(item.keys())
            x = []
            for i in item[keys[1]]:
                x.append(i['name'])
            out[item[keys[0]]] = x
            print(out)
10
  • Additional note there are trailing digits in every name; like 01 02 etc. if you want to remove them instead of appending i['name'] directly make the necessary changes and then append. Commented Oct 22, 2022 at 1:50
  • I get an error: line 8, in <module> for i in item[keys[1]]: IndexError: list index out of range Commented Oct 22, 2022 at 20:26
  • This is probably because one item in your List of dicts not having any corresponding name_list in the dictionary. To counter this you can just put a conditional to check if keys has 2 items. if Len(keys) < 2: continue Commented Oct 23, 2022 at 1:49
  • Now it don't return error but it print with repetitions, i. e. it firstly print "linia 1:", then "linia 1:", "linia 3:" and so on, instead of printing all "linia 1:", "linia 3:", ... at once. Commented Oct 23, 2022 at 11:55
  • The dictionary should contain "linia" 's number as key in format int. Commented Oct 23, 2022 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.