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.
How to access a dictionary value with a list index number in python?
the problem is that list1[0]
is a dictionary, and when using the way you are doing in a for loop, it'l iterate over the keys of that dictionary
so in your case, for the first iteration the e
variable is of type int
with the value 1, in the second iteration it has the value 2
.
so if you want to iterate over the keys, and values of a dictionary you should use
for key, val in list1[0].items():
print('key: {}, value {}'.format(key, val))
Access dict keys and list elements by same index to loop over and assign values
I am using Python 3.7.1 (it retains dict order) and the below answer works.However I welcome any better and efficient answer and looking forward to it
for i in range(len(key_list)):
a = list(dataFramesDict)[i]
dataFramesDict[a]['unit'] = unit_list[i]
how to get access elements of a dictionary by its index?
You need to convert the keys of the dictionary to a list in order to access by its index. This method has an O(n)
complexity compared to the access by key values directly to the dictionary (hash table), which results in a constant O(1)
time complexity:
a={'ali':10 , 'reza':19 , 'sara':15}
print(a[list(a.keys())[0]]) #Here you are getting a list of all keys of the dictionary by calling list(a.keys()), and accessing a specific element of that list with [:] operator
Output:
10
Accessing dict_keys element by index in Python3
Call list()
on the dictionary instead:
keys = list(test)
In Python 3, the dict.keys()
method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:
>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'
Related Topics
Pytest - Specify Log Level from the Cli Command Running the Tests
How to Set Python's Default Version to 3.X on Os X
Is _Init_.Py Not Required for Packages in Python 3.3+
Using Property() on Classmethods
Cannot Open Include File: 'Io.H': No Such File or Directory
Is There a Built-In Function to Print All the Current Properties and Values of an Object
And' (Boolean) VS '&' (Bitwise) - Why Difference in Behavior with Lists VS Numpy Arrays
Visibility of Global Variables in Imported Modules
Pandas Get Topmost N Records Within Each Group
Python For-In Loop Preceded by a Variable
How to Print a Variable Name in Python
Pg_Config Executable Not Found
Having Django Serve Downloadable Files
Python Multiprocessing + Subprocess Issues
Handling Spreadsheet Data Through the Clipboard in Gtk
How to Direct Output to a File When There Are Utf-8 Characters
Remove Duplicates by Columns A, Keeping the Row with the Highest Value in Column B