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
Copyvalue_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.
Answer from NPE on Stack OverflowIn 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
Copyvalue_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.
Let us take an example of dictionary:
Copynumbers = {'first':0, 'second':1, 'third':3}
When I did
Copynumbers.values()[index]
I got an error:'dict_values' object does not support indexing
When I did
Copynumbers.itervalues()
to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'
Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.
Copytuple(numbers.items())[key_index][value_index]
for example:
Copytuple(numbers.items())[0][0] gives 'first'
if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use
Copylist(list(numbers.items())[index])
Can a tuple be used as a dictionary key?
How to get (first) element from list of dicts where dict key equals a specific value?
Is there a way to lookup a value in a dictionary?
Using get() with nested dictionary.
Videos
...This is a bit crazy but, let's say I have the following list:
my_dict = [{"key" = 1, "foo" = 'a'},
{"key" = 2, "foo" = 'b'},
{"key" = 3, "foo" = 'c'},
{"key" = 4, "foo" = 'd'}]
...And I wanted to get the value of "foo" where "key" = 3.
How would I write that assignment?
Hey all, hoping someone can help me out. I'm new to python but getting the hang of it. I'm using subprocess to run ffprobe and have it return JSON. Depending on the file I'm analyzing, some properties may not exist and won't appear in the JSON results. If i print this it works:
dvd_properties['streams'][0]['duration']
But I'm having trouble using the get() method on it:
dvd_properties.get('streams').get('0').get('duration'), "Unknown"
I'm trying to use get() so I have a default value if there are no results in the JSON output. I'm testing on a file that does have the duration element to make sure it works if I have data.
Can anyone lend me a hand? I've tried to search but I can't find anything about this particular situation. I have the get('parent').get('child') working for simple cases, so I'm hoping it will work here as well and I'm just missing something obvious.
Thanks in advance, I do appreciate it.