Warm tip: This article is reproduced from serverfault.com, please click

I can't do anything with python dict?

发布于 2020-11-28 02:45:29

Im really stuck with a little problem that I have.

diccionario_antiguos = {}
            
    data = open('Currency_price.json')
    for i in data:
        diccionario_antiguos = i

Currency_price.json is a file which contains a dictionary like this:

{"Dolar": ["80,25", "86,25"], "Euro": ["96,59", "97,04"]}

With the key being the currency and the value a list with its prices.

My problem is that after I pass all the info to diccionario_antiguos, I can't manipulate anything inside it.

if i do for instance:

print(diccionario_antiguos.get('Dolar')

I get 'str' object has no attribute 'get'

If I do

print(diccionario_antiguos['Dolar']

I get string indices must be integers

And then I said "Oh, I should have tu use integers", so I did:

print(diccionario_antiguos[0])

No Exception there, but I get [] (when I printed the whole dictionary and I KNOW the data IS there).

I don't know what's happening, because if I apply this methods with any dictionary, they'll work, even if the key is a String.

Any solutions? Thank you!

Questioner
Oto
Viewed
0
frankr6591 2020-11-28 10:59:13

Here is code for json and dict...

import json
j = '''{"Dolar": ["80,25", "86,25"], "Euro": ["96,59", "97,04"]} '''
jDict = json.loads(j)
print(jDict)
print("Dolar List", jDict['Dolar'])
print("Euro  List", jDict['Euro'])

# Write Dict to json file
fn = 'Currency_price.json'
with open(fn, 'w') as fio:
    json.dump(jDict, fio)

# Read Json file
with open(fn, 'r') as fio:
    j2Dict = json.load(fio)

print("\n-------\n")

print(j2Dict)
print("Dolar List", j2Dict['Dolar'])
print("Euro  List", j2Dict['Euro'])

output

{'Dolar': ['80,25', '86,25'], 'Euro': ['96,59', '97,04']}
Dolar List ['80,25', '86,25']
Euro  List ['96,59', '97,04']

-------

{'Dolar': ['80,25', '86,25'], 'Euro': ['96,59', '97,04']}
Dolar List ['80,25', '86,25']
Euro  List ['96,59', '97,04']