简体   繁体   中英

Python 3 - how do I list the first 5 values from a dictionary?

I load a dictionary-data from a JSON like this:

list_of_people = json.load(open('list_of_people.json'))

and I would like to pick the first 5 value items from this JSON. I tried to do it this way:

print(data.values()[0:5])

However, this resulted into

TypeError: 'dict_values' object is not subscriptable

How do I list that?

just cast values to a list, like this:

print(list(data.values())[0:5])

NOTE: if you are using Python 3.5 and earlier, dictionaries do NOT maintain order, in that case "the first 5 elements" is not really a thing...

if you have a specific way to sort them, you can use sorted to sort, and only then slice with [0:5]

if you do not want to create an intermediate list of possibly many elements you could use itertools.islice :

from itertools import islice

print(dict(islice(list_of_people.items(), 5)))   # shortened dict
print(list(islice(list_of_people.values(), 5)))  # shortened values

note that first items of a dictionary only makes sense from python 3.5 and later; before that dictionaries were unordered.

You can also try this:

import json
person = '{"name": "Bob", "languages": ["English", "Fench"], "location": "mumbai", "interests": "NLP"}'
person_dict = json.loads(person)
print(list(person_dict.values())[0:2])

output

 ['Bob', ['English', 'Fench']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM