1

How to access nested dictionary in python. I want to access 'type' of both card and card1.

data = {
'1': {
'type': 'card',
'card[number]': 12345,
},
'2': {
'type': 'wechat',
'name': 'paras'
}}

I want only type from both the dictionary. how can i get. I use the following code but getting error:

>>> for item in data:
...     for i in item['type']: 
...             print(i)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: string indices must be integers

3 Answers 3

5

You can use:

In [120]: for item in data.values():
     ...:     print(item['type'])

card
wechat

Or list comprehension:

In [122]: [item['type'] for item in data.values()]
Out[122]: ['card', 'wechat']
Sign up to request clarification or add additional context in comments.

2 Comments

how to use using get().
You don't need to use get() here, but if you want, use item.get('type')
2

When you iterate a dictionary, e.g. for item in data, you are iterating keys. You should use a view which contains the information you require, such as dict.values or dict.items.

To access the key and related type by iteration:

for k, v in data.items():
    print(k, v['item'])

Or, to create a list, use a list comprehension:

lst = [v['item'] for v in data.values()]
print(lst)

Comments

-2

nested dict

from a nested python dictionary like this, if I want to access lets, say article_url, so I have to program like this

[item['article_url'] for item in obj.values()]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.