If I have a list of dictionaries in a python script, that I intend to later on dump in a JSON file as an array of objects, how can I index the keys of a specific dictionary within the list?
Example :
dict_list = [{"first_dict": "some_value"}, {"second_dict":"some_value"}, {"third_dict": "[element1,element2,element3]"}]
My intuitive solution was dict_list[-1][0] (to access the first key of the last dictionary in the list for example). This however gave me the following error:
IndexError: list index out of range
the key inputted into the dictionary will pick the some value in the format dict = {0:some_value}
to find a specific value:
list_dictionary = [{"dict1":'value1'},{"dict2","value2"}]
value1 = list_dictionary[0]["dict1"]
the 'key' is what you have to use to find a value from a dictionary
Example:
dictionary = {0:value}
dictionary[0]
in this case it will work
but to pick the elements we will do
values = []
for dictionary in dict_list:
for element in dictionary:
values.append(dictionary[element])
Output:
['some_value', 'some_value', ['element1', 'element2', 'element3']]
dict_list = [{"first_dict": "some_value"}, {"second_dict":"some_value"}, {"third_dict": ['element1','element2','element3']}]
If your dict look like this you can do as well
dict_list[-1]["third_dict"]
You can't access 'the first key' with a int since you have a dict
You can get the first key with .keys() and then
dict_list[-1].keys()[0]
By using dict_list[-1][0], you are trying to access a list with a list, which you do not have. You have a list with a dict key within a list.
Taking your example dict_list[-1][0]:
When you mention dict_list you are already "in the list".
The first index [-1] is referring to the last item of the list.
The second index would only be "usable" if the item mentioned in the previous index were a list. Hence the error.
Using:
dict_list=[{"first_dict": "some_value"}, {"second_dict":"some_value"},{"third_dict": [0,1,2]}]
to access the value of third_dict you need:
for value in list(dict_list[-1].values())[0]:
print(value)
Output:
0
1
2
If you know the order of dictionary keys and you are using one of the latest python versions (key stays in same order), so:
dict_list = [
{"first_dict": "some_value"}
, {"second_dict":"some_value"}
, {"third_dict": ["element1", "element2", "element3"]}
]
first_key = next(iter(dict_list[-1].keys()))
### OR: value
first_value = next(iter(dict_list[-1].values()))
### OR: both key and value
first_key, first_value = next(iter(dict_list[-1].items()))
print(first_key)
print(first_key, first_value)
print(first_value)
If you have the following list of dictionaries:
dict_list = [{"key1":"val1", "key2":"val2"}, {"key10":"val10"}]
Then to access the last dictionary you'd indeed use dict_list[-1] but this returns a dictionary with is indexed using its keys and not numbers: dict_list[0]["key1"]
To only use numbers, you'd need to get a list of the keys first: list(dict_list[-1]). The first element of this list list(dict_list[-1])[0] would then be the first key "key10"
You can then use indices to access the first key of the last dictionary:
dict_index = -1
key_index = 0
d = dict_list[dict_index]
keys = list(d)
val = d[keys[key_index]]
However you'd be using the dictionary as a list, so maybe a list of lists would be better suited than a list of dictionaries.
Related
I have a data that looks like this
dict1 = [[{'num1':1, 'num2':2, 'num3':3}], [{'num1':4,'num2':5, 'num3':6}]]
How do I go inside the list where it contains the dictionary to select a specific key to display.
I seem to be getting a lot if list index out of range error.
Here's my current code:
for items in dict1:
for index in range(len(dict1)):
print(items[index]['num1'])
It's rather obvious that your dict1 is not a single-depth list, it's a list of list, so iterate it this way:
dict1 = [[{'num1':1, 'num2':2, 'num3':3}], [{'num1':4,'num2':5, 'num3':6}]]
for t in dict1:
obj = t[0]
for key in obj:
print(key,obj[key])
i'm using an api call in python 3.7 which returns json data.
result = (someapicall)
the data returned appears to be in the form of two nested dictionaries within a list, i.e.
[{name:foo, firmware:boo}{name:foo, firmware:bar}]
i would like to retrieve the value of the key "name" from the first dictionary and also the value of key "firmware" from both dictionaries and store in a new dictionary in the following format.
{foo:(boo,bar)}
so far i've managed to retrieve the value of both the first "name" and the first "firmware" and store in a dictionary using the following.
dict1={}
for i in result:
dict1[(i["networkId"])] = (i['firmware'])
i've tried.
d7[(a["networkId"])] = (a['firmware'],(a['firmware']))
but as expected the above just seems to return the same firmware twice.
can anyone help achive the desired result above
you can use defaultdict to accumulate values in a list, like this:
from collections import defaultdict
result = [{'name':'foo', 'firmware':'boo'},{'name':'foo', 'firmware':'bar'}]
# create a dict with a default of empty list for non existing keys
dict1=defaultdict(list)
# iterate and add firmwares of same name to list
for i in result:
dict1[i['name']].append(i['firmware'])
# reformat to regular dict with tuples
final = {k:tuple(v) for k,v in dict1.items()}
print(final)
Output:
{'foo': ('boo', 'bar')}
I'm new to python and I was wondering if there's a way for me to pull a value at a specific index. Let's say I have a key with multiple values(list) associated with it.
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
Let's say I want to iterate through values and print out the value if it's equal to 'DOG'. Do Values, Key pairs have a specific index associated with the position of Values?
I've try reading up on dict and how it works apparently you can't really index it. I just wanted to know if there's a way to get around that.
You can perform the following (comments included):
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for keys, values in d.items(): #Will allow you to reference the key and value pair
for item in values: #Will iterate through the list containing the animals
if item == "DOG":
print(item)
print(values.index(item)) #will tell you the index of "DOG" in the list.
So maybe this will help:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
print(animal)
Update -What if I want to compare the string to see if they're equal or not... let say if the value at the first index is equal to the value at the second index.
You can use this:
d = {'ANIMAL' : ['CAT','DOG','FISH','HEDGEHOG']}
for item in d:
for animal in (d[item]):
if animal == "DOG":
if list(d.keys())[0] == list(d.keys())[1]:
print("Equal")
else: print("Unequal")
Keys and values in a dictionary are indexed by key and do not have a fixed index like in lists.
However, you can leverage the use of 'OrderedDict' to give an indexing scheme to your dictionaries. It is seldom used, but handy.
That being said, dictionaries in python3.6 are insertion ordered :
More on that here :
Are dictionaries ordered in Python 3.6+?
d = {'animal': ['cat', 'dog', 'kangaroo', 'monkey'], 'flower': ['hibiscus', 'sunflower', 'rose']}
for key, value in d.items():
for element in value:
if element is 'dog':
print(value)
does this help? or, you want to print index of key in dictionary?
I have created a dictionary with empty values as "dictionary". I also have a list named contig_list_numbers(first list in the output) . What i have been trying to do is to append the values from contig_list_numbers into the
the dictionary values.
what i want is to place all string values after ":" in list as the values in the dictionary.ex- contig1000:254', 'contig1000:170', 'contig1000:1114', 'contig1000:2199' this to be converted into {contig1000 : [254,170,1114,2199]}
can someone help me out ??
first list is contig_list_numbers
last is dictionary with empty values
You can split the string by : to get key and value, store them to dictionary
and append the value if key already exist.
So the solution would be:
dictionary = {}
contig_list_numbers = ['contig1000:254', 'contig1000:170', 'contig1000:1114', 'contig1000:2199']
for astring in contig_list_numbers:
key, value = astring.split(":")
if key not in dictionary:
dictionary[key] = [value]
else:
dictionary[key].append(value)
Here is my code:
for response in responses["result"]:
ids = {}
key = response['_id'].encode('ascii')
print key
for value in response['docs']:
ids[key].append(value)
Traceback:
File "people.py", line 47, in <module>
ids[key].append(value)
KeyError: 'deanna'
I am trying to add multiple values to a key. Throws an error like above
Check out setdefault:
ids.setdefault(key, []).append(value)
It looks to see if key is in ids, and if not, sets that to be an empty list. Then it returns that list for you to inline call append on.
Docs:
http://docs.python.org/2/library/stdtypes.html#dict.setdefault
If I'm reading this correctly your intention is to map the _id of a response to its docs. In that case you can bring down everything you have above to a dict comprehension:
ids = {response['_id'].encode('ascii'): response['docs']
for response in responses['result']}
This also assumes you meant to have id = {} outside of the outermost loop, but I can't see any other reasonable interpretation.
If the above is not correct,
You can use collections.defaultdict
import collections # at top level
#then in your loop:
ids = collections.defaultdict(list) #instead of ids = {}
A dictionary whose default value will be created by calling the init argument, in this case calling list() will produce an empty list which can then be appended to.
To traverse the dictionary you can iterate over it's items()
for key, val in ids.items():
print(key, val)
The reason you're getting a KeyError is this: In the first iteration of your for loop, you look up the key in an empty dictionary. There is no such key, hence the KeyError.
The code you gave will work, if you first insert an empty list into the dictionary under to appropriate key. Then append the values to the list. Like so:
for response in responses["result"]:
ids = {}
key = response['_id'].encode('ascii')
print key
if key not in ids: ## <-- if we haven't seen key yet
ids[key] = [] ## <-- insert an empty list into the dictionary
for value in response['docs']:
ids[key].append(value)
The previous answers are correct. Both defaultdict and dictionary.setdefault are automatic ways of inserting the empty list.