bernando_vialli
bernando_vialli

Reputation: 1019

How to extract the value only in a key-value pair in a list of dictionaries when a key is a certain value

I have a list of dictionaries that looks something like (this is a very tiny subset of the actual data):

[{'utterance': 10,'id': 'output454', 'utterance': 'this is nice'}]

I want to extract every value where the key is 'utterance' so in this example, I would like the output to be (I do not want to include the key in the output itself):

'this is nice'

I have tried doing a few things, none of which worked (none of the below worked):

[key for key, val in data.items() if key== "'utterance'"]

for k, v in data.iteritems():
    if k == '"utterance":':
        print(data[k])

I would appreciate any help. Thank you

Upvotes: 0

Views: 2509

Answers (4)

Rohan Vardhan
Rohan Vardhan

Reputation: 118

The keys in Python dictionary should be unique i.e, you cannot have duplicated keys in a python dictionary.

However, if you want a key to store multiple values, you can use defaultdict.

For example,

from collection import defaultdict
d = defaultdict(list)
d = {'utterance': [10, 'this is nice'],'id': ['output454']}
print(d.get('utterance', None))

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 371

Problem: The problem here is that python dictionary does not allow duplicate keys so the object 'utterance': 10 is being discarded while the initialization.

Solution: Change your object format like

data = [{
    'utterance': [10,'this is nice'],
    'id': 'output454'
}]

Upvotes: 0

jfaccioni
jfaccioni

Reputation: 7509

Using a list comprehension here becomes easier if you first loop over the outer list:

>>> mylist = [{'utterance': 10,'id': 'output454', 'utterance': 'this is nice'}]
>>> values = []
>>> for dictionary in mylist:
...     values.extend([v for k, v in dictionary.items() if k == 'utterance'])
... 
>>> values
['this is nice']

Upvotes: 1

VeNoMouS
VeNoMouS

Reputation: 312

data = [{'utterance': 10,'id': 'output454', 'utterance': 'this is nice'}]
for elem in data:
    print('{}'.format(data[elem].get('utterance')))

or , if only the one element in the list..

data = [{'utterance': 10,'id': 'output454', 'utterance': 'this is nice'}]
print('{}'.format(data[0].get('utterance')))

Upvotes: 0

Related Questions