Sunil Gautam
Sunil Gautam

Reputation: 49

Python list of dict

I have this list of dictionary

dictList = [
    {'value': 'me'}, {'value': 'you'}, {'value': 'him'},
    {'value': 'her'}, {'value': 'them'}, {'value': 'they'}
]

I know how to get the value given the key like this

print(item for item in dictlist if item["value"] == "me").next()

which prints out

{'value': 'me'}

However I want to print just the 'me' 'you' etc and not 'value'. So the result looks like

{'me', 'you', 'him', 'her','them', 'they'}

Thanks

Upvotes: 1

Views: 1869

Answers (5)

abby sobh
abby sobh

Reputation: 1624

Another list of dicts problem! Try using the pandas package to simply refer to keys as column headers and group values using the same key:

import pandas as pd

dictList = [
{'value': 'me'}, {'value': 'you'}, {'value': 'him'},
{'value': 'her'}, {'value': 'them'}, {'value': 'they'}
]

df = pd.DataFrame(dictList)
dictList_values = df['value'].tolist()

Added some benchmarking, using pandas outperforms on large scale sets. Here I've created a set with 200k entries as a "large" case. The small case is the given 6 entries:

setup_large = "dictList = [];\
[dictList.extend(({'value': 'me'}, {'value': 'you'}, {'value': 'him'},\
    {'value': 'her'}, {'value': 'them'}, {'value': 'they'})) for _ in range(25000)];\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(dictList);"

setup_small = "dictList = [];\
dictList.extend(({'value': 'me'}, {'value': 'you'}, {'value': 'him'},\
    {'value': 'her'}, {'value': 'them'}, {'value': 'they'}));\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(dictList);"

method1 = "[d['value'] for d in dictList if 'value' in d]"
method2 = "df['value'].tolist()"

import timeit
t = timeit.Timer(method1, setup_small)
print('Small Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_small)
print('Small Method Pandas: ' + str(t.timeit(100)))

t = timeit.Timer(method1, setup_large)
print('Large Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_large)
print('Large Method Pandas: ' + str(t.timeit(100)))

#Small Method LC: 0.000217914581299
#Small Method Pandas: 0.00168395042419
#Large Method LC: 3.89074897766
#Large Method Pandas: 0.189871072769

Upvotes: 0

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44112

Using reduce

If you like very unreadable method, here is one:

>>> reduce(list.__add__, map(dict.values, dictList))
>>> ['me', 'you', 'him', 'her', 'them', 'they']

Explained:

dict.values: this is method, which is usually applied to a dictionary in the way: {"key": 12, "sleutel": 44}.values() and returns only values for all the keys in the dict, thus [12, 44].

By dict.values we refer explicitly to that method and call map to apply this to each item in your dictList.

From map(dict.values, dictList) you get [['me'], ['you'], ['him'], ['her'], ['them'], ['they']].

Then you add one sublist to another.

['me'] + ['you'] + ['him'] + ['her'] + ['them'] + ['they']

To do that on a list, use reduce, which takes works in the way:

>>> res = ['me'] + ['you']
>>> res = res + ['him']
>>> res = res + ['her']
>>> res = res + ['them']
>>> res = res + ['they']

and finally you get what you asked for.

Using sum

The solution can be shortened by means of sum providing initial value of []:

>>> sum(map(dict.values, dictList), [])
>>> ['me', 'you', 'him', 'her', 'them', 'they']

Upvotes: 0

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44112

Another approach is to collect values() from all dictionaries in the list. This will work regardless of what keys are used (you use "value").

>>> dictList = [
    {'value': 'me'}, {'value': 'you'}, {'value': 'him'},
    {'value': 'her'}, {'value': 'them'}, {'value': 'they'}
]
>>> [dct.values()[0] for dct in dictList]
['me', 'you', 'him', 'her', 'them', 'they']

Upvotes: 0

Ryan Haining
Ryan Haining

Reputation: 36822

You can extract the values you are looking for with a list comprehension, or use it as a generator expression if you don't need to preserve it

[d['value'] for d in dictList if 'value' in d]

this will only do the d['value'] lookup if the key 'value' exists in the dict

If you know that all of the dicts will have that key, you can drop the filter

[d['value'] for d in dictList]

Upvotes: 2

John Gordon
John Gordon

Reputation: 33335

for d in dictList:
    if 'value' in d:
        print d['value']

Upvotes: 4

Related Questions