Problem when interacting with dict Python


I have my following code:

for noms in json_obj['nom']:
    Type = noms.split("-")
    x = Type[1]
    y = Type[2]

Where json_obj['nom'] has the following values:

[{u'nom': u'7558-802'}, {u'nom': u'7558-998'}]

What I'm looking for is that in "x" the value 7558 be saved and in "y" 802 and 998 be saved

But when I run my program, it sends me the following error:

Type = noms.split("-")
AttributteError: 'dict' object has no attribute 'split'
asked by José McFly Carranza 01.03.2017 в 01:11

2 answers


If I understand what you want, in json_obj['nom'] you have a list of dictionaries that only interest you the values of the key nom . These values are "tuples" that you want to group by the first element of the tuple.

That is, from:

[{u'nom': u'7558-802'}, {u'nom': u'7558-998'}]

you want to go to

(x,y) = ('7558',['802','998'])

The first thing is to take out the list of tuples:

tuplas = [s["nom"].split("-") for s in json_obj['nom']]

# tuplas --> [['7558', '802'], ['7558', '998']]

To group by the first element of the tuples there would be several ways to do it, but a simple one:

d = {}
for k,v in tuplas:
    d.setdefault(k, []).append(v)

# d -> {'7558': ['802','998']}

Almost there. The last thing left is to iterate between the items of the dictionary:

for x,y in d.items():
answered by 01.03.2017 в 13:40

It happens that json_obj['nom'] is a list that contains two dictionaries.

If you say that json_obj ['nom'] has [{u'nom': u'7558-802'}, {u'nom': u'7558-998'}] I can do:

lista = [{u'nom': u'7558-802'}, {u'nom': u'7558-998'}]

and seeing its type, the matter is clarified:

>>> type(lista)

If you could do something like this to get the required element and be able to divide it.

>>> for noms in lista:
...     Type = noms['nom'].split('-')
...     x = Type[0]
...     y = Type[1]

The algorithm you raise stores in x and in y only the last cycle for , so it only contains x = 7558 and y = 998 . There are several alternatives for what you want, but you must open a new question, since the subject is different from the current one.

answered by 01.03.2017 в 01:38