Update value of a nested key by reference in python 3 - python

I have the following dictionary:
watch_list= {'videos': [{'systemId': 'qre', 'duration': 19}, {'systemId': 'abc', 'duration': 19}]}
now I wanted to check if the systemId already exists in the dictionary and if yes then update duration by systemId.
hence I am trying the following code:
def update_duration(watch_list,system_id,duration):
watch_history= next((a for a in watch_list if a['systemId'] == system_id), None)
if watch_history:
watch_history['duration'] =duration
return watch_history
but this gives me an error:
*** TypeError: string indices must be integers
I am new to python, I have read stack overflow other solutions but couldnt made it work. can anyone help me a little here, on how to update the value by the systemId?
I am using python 3 and flask

When you iterate through a dictionary with something like
my_dictionary = { 'hello' : ['I', 'am', 'a', 'dictionary'] }
for entry in my_dictionary:
print entry
The output will be hello, as it iterates through its keys by default. As it appears you're actually wanting to iterate through the dictionary's values, you'll want to call the values() function, or itervalues() in Python2.
Beyond that, you're then running into an issue with your generator comprehension's if statement. At that point, your a variable is holding a list of dictionaries---what used to be the value found by watch_list['videos'].

Related

Iterating over A dict to access a specific key value

I have a list of dicts ('sortings') that I am trying to iterate through to access a values in one specific key of each dict. My code keeps saying that there is a key error for the desired value in the dict. If I print inside the for loop, it prints with the values entered but once I exit the for loop it says there is a key error.
for i in range(sort_len):
sentence = sortings[i]['content']
containing_messages.append(sentence)
print(containing_messages)
This is an answer for my understanding of the question. I would require the given input and expected output to provide a better answer.
list_of_dicts = [{'keya':'value1_1','keyb':'value2_1','keyc':'value3_1'},
{'keya':'value1_2','keyb':'value2_2','keyc':'value3_2'},
{'keya':'value1_3','keyb':'value2_3','keyc':'value3_3'}]
list_of_key_values = [my_dict['keyb'] for my_dict in list_of_dicts]
print list_of_key_values

Using append to get data from a nested list

Currently my code is like this:
.append("Last Name {}, First Name {} Stats: {}".format(result["L_Name"], result["F_Name"], result["Stats"]))
this code works but the output isn't exactly the ones I want the code to display.
the problem is that the Stats has another list
L_Name: Doe
F_Name: John
Contribution:
Month
Value
Returns
is there a way to just pick out only the Value from the Stats by just adding or changing something in my append?
specifically in this part?
, result["Stats"]))
If you are only after one value of Stats, you can get the value at a certain index. Assuming Value is at index 1 and Stats is a standard Python list:
, result["Stats"][1]))
Notice that you can access the items of the JSON structure in the format string itself. This is clearer than using positional arguments if the format string is very complicated. Additionally, you can pass the whole dictionary into format_map:
l.append("Last Name {L_Name}, First Name {F_Name} Stats: {Stats[Value]}"
.format_map(result))
(In Python 2, format_map doesn't exist, use format(**result) instead.
In the future please consider posting working code only so we can reproduce your issue. I am going to assume result['stats'] is a dictionary and the bulleted list are key:value pairs.
You can access the "Contribution" key of your result["Stats"] dictionary which results in list. You can then slice the second element of the list with [1].
_.append("Last Name {}, First Name {} Stats: {}".format(
result["L_Name"],
result["F_Name"],
result["Stats"]["Contribution"][1]))
This assumes result['stats'] looks like:
result['stats'] = {
'L_Name': 'Doe',
'F_Name': 'John',
'Contribution': [Month, Value, Returns]}
Thanks everyone I was able to get a hint from your answers
result["Stats"]["Contribution"][1]
worked well for me

Getting an dict by name with in a list with an element key within a variable

data = {
"items" : [{"potion" : 1}, {"potion2" : 1}]
}
print(data["items"][0]["potion"])
So, here's the jiz. I want to get potion2 without providing number like [0] but i can't because some variables has 5 items within the list while another one might have 3 items so providing a number might not giving me what i need. Is there a way to get potion2 without providing that number before it?
I'm assuming you don't want to provide the index because hard coding it will not work in all circumstances.
You can just pull out any items in the list which have that key.
Build a list of any items, which have that key. It might ordinarily be just one, but the container itself does not enforce that only one entry can have that key.
After that you can either iterate over the list or check if the returned value is empty and just take the first element.
>>> data = {'items': [{'potion': 1}, {'potion2': 1}]}
>>> e = filter(lambda i: 'potion' in i, data['items'])
>>> for i in e:
... print(i['potion'])
...
1
Or to pull out only the first element. I realize you said no indices, but this index is applied to the filtered list and we check that its not empty first, so it's a valid thing to do.
>>> if e:
... print(e[0]['potion'])
...
1

Python string: how to query a dictionary inside a list, which are inside a dictionary

The goal: from the string below I need to extract, side by side, the 'key' value and the 'query' value, which are returned by an API.
I'm not a Python expert, but to me it seems that the API that I'm hitting returns a dictionary inside a list, which themselves are inside a dictionary.
That seems to be the crux of the issue [the involvement of the list]. Note, the API may return multiple lines such as the one below.
{'Condition1': 'True', 'Load': 'Normal', 'query': 'xyz', 'results': [{'F1': 'abc', 'F2': 'def','Key': 'dfg4325'}]}
from the example above, I'm trying to retrieve a combined string that would be i.e. like a CSV as follows:
'xyz','dfg4325'
I've tried a number of tactics but nothing is working. The 'key' field inside the list's dictionary is always alpha-numeric - otherwise I'd have a hack for it.
Any thoughts would be appreciated. I googled this and just can't hit the right answer.
You can iterate a dict and a list to find the value of 'key', for example,
for key, val in response.items():
if isinstance(val, list):
for dic in val:
if 'Key' in dic:
val_of_key = dic.get('Key')
break
if isinstance(search_response["results"], list):
for dic in search_response["results"]:
if "Key" in dic:
val_of_key = dic["Key"]
decoded_Key = (val_of_key + "|" + search_response["query"]+ "\n")
# setup a dummy text file in the same fldr as the pycharm project
# appends the results to a text
with open("dummy.txt", "a") as query_file:
query_file.write(decoded_Key)

python create new dict key from the value

I have a array of hashes like:
detail = [{'name': 'Adam'}, {'name': 'Jackie'}]
Now what I want to do is create a new dict like:
{'name' : 'Sandra'}
What I did was:
for i in detail:
for key_in_i in i:
dict(key_in_i = 'Sandra')
What I would like to get is {'Name': 'Sandra'}. But if I do this I am getting {'key_in_u': 'Sandra'} because I have set the key as key_in_i. I don't know how to access the value of key from for loop to the new dict. If it was in Ruby I would have done #{key_in_i} and it would have given me the required value. I also tried new_dict = dict("%s" %key = i[key]) but it gives me error key cannot be the expression. I would be thankful if anyone could help me solve this issue!
The easiest solution in this particular case is
for i in detail:
print dict.fromkeys(i, "Sandra")
You could also use a dictionary literal:
for i in detail:
for key_in_i in i:
{key_in_i: "Sandra"}
(Not sure what you are actually trying to achieve since your example code is effectively doing nothing.)

Categories