How to Index into a Dictionary

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can create a list of keys for a dictionary d using keys = list(d), and then access keys in the list by index keys[i], and the associated values with d[keys[i]].

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

Accessing dictionary value by index in python

In Python versions before 3.7 dictionaries were inherently unordered, so what you're asking to do doesn't really make sense.

If you really, really know what you're doing, use

value_at_index = list(dic.values())[index]

Bear in mind that prior to Python 3.7 adding or removing an element can potentially change the index of every other element.

Add an index to dictionary in for-loop

list_test = []
for i, row in first_test.iterrows():
for con, val in zip(row['content'].values(), row['value'].values()):
for un_con, un_val in zip(con, val):
list_test += [
dict(index=i,
data_content=un_con,
data_values=un_val,
)]

pd.DataFrame(list_test)

change value dictionary by index

This should work:

letters = {0: ['A', 'B'], 1: ['C', 'Z']}
for key in letters:
new_list = []
for i in letters[key]:
i = i.lower()
new_list.append(ord(i) - 97)
letters[key] = new_list

I subtracted 97 instead of 96 (The reason why 96 is subtracted is well explained in this post: Convert alphabet letters to number in Python) because it seems like you want everything to be shifted so that A is 0 not 1 like it would usually be.

Output:

{0: [0, 1], 1: [2, 25]}

How to get the index with the key in a dictionary?

Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

For those using Python 3

>>> list(x.keys()).index("c")
1

How to convert a list to a dictionary with indexes as values?

You can get the indices of a list from the built-in enumerate. You just need to reverse the index-value map and use a dictionary comprehension to create a dictionary:

>>> lst = ['A', 'B', 'C']
>>> {k: v for v, k in enumerate(lst)}
{'A': 0, 'C': 2, 'B': 1}

Using an indexed list as a value in data dictionary

When you're iterating over each row, also iterate over the elements 3 onwards (row[3:]). You can use the enumerate() function with a second argument to have the index start at 1. Then, construct your key using the first three elements of your row, and the new "index" of the item. Then, simply assign that value to that key in the dictionary. No need for multidicts.

csv_capacityatest = [[1, 1, 3, 1, 10, 5, 10],
[1, 2, 3, 7, 5, 3, 8 ],
[1, 4, 5, 9, 7, 2, 8 ],
[2, 1, 2, 0, 0, 0, 0 ],
[2, 3, 5, 6, 4, 3, 2 ],
[2, 5, 6, 7, 10, 4, 4 ],]

mydict_capacityatest = {}

for row in csv_capacityatest:
key_start = row[0:3]
for index, item in enumerate(row[3:], 1):
key = tuple(key_start + [index])
mydict_capacityatest[key] = item

Which gives this dict:

{(1, 1, 3, 1): 1,
(1, 1, 3, 2): 10,
(1, 1, 3, 3): 5,
(1, 1, 3, 4): 10,
(1, 2, 3, 1): 7,
(1, 2, 3, 2): 5,
(1, 2, 3, 3): 3,
(1, 2, 3, 4): 8,
(1, 4, 5, 1): 9,
(1, 4, 5, 2): 7,
...
}


Related Topics



Leave a reply



Submit