accessing specific elements of dictionary given a list of index

Josselin

l would like to get access to a specific values of my dictionary given their indices. When l given only one index or a continuing list of indices [0:30] it works as follow:

print(labels.keys()[0])
'IceDancing'
print(labels.keys()[0:3])
['IceDancing', 'IceDancing', 'HighJump']

However when l try to access specific indices as follow :

indices=[3,4,45,8,56]
labels.keys()[indices]

l get the following error

*** TypeError: list indices must be integers, not list

Thank you for your help

jpp

As mentioned, dictionaries in Python 2.7 are not ordered. You should not assume any particular or consistent order when you use dict.keys.

Nonetheless, what you are requesting is possible with operator.itemgetter. Here's a trivial example:

from operator import itemgetter

d = {i+10: i for i in range(100)}
idx = [3,4,45,8,56]

print itemgetter(*idx)(d.keys())

# (13, 14, 55, 18, 66)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Accessing NumPy array elements not in a given index list

PYTHON: Accessing elements of a list of lists in a dictionary

How to append elements into dictionary at specific index swift

Accessing the list of list specific number elements and merging using python

Delete elements from python array with given index of elements as list

Remove elements from a List at a specific index

Error accessing DateTime List. "Index out of bounds" or "contains no elements"

Accessing a dictionary inside a list

Accessing a list as the key for a dictionary

Replacing elements inside a dictionary Python given a list of current items

Accessing specific elements in an ArrayList

Accessing specific elements in a list of tuples in f# without libraries

map list of objects to be with specific field based on given list of the field elements

Finding index number of dictionary item in a list based on a given value

Accessing elements of the dictionary in a loop in python

Accessing elements in a list Python

Accessing elements in list in r

accessing list elements in python

Most efficient way of adding elements given the index list in numpy

Slicing a list to extract the last k and next k elements given an index

Swapping elements based on index given from another list

python accessing elements in a dictionary inside dictionary

accessing name of an index in a list

Pythonic way of counting max elements by index in a dictionary with list values

Display list elements using index of dictionary in Jinja(Django)

How to remove the list of dictionary elements with the same specific key-value

IndexError: list index out of range while accessing data from list inside a dictionary

Given the pandas dataframe column, how to replace elements X in a nested list with the values in dictionary if X is a key in a dictionary?

retrieve specific elements of dictionary