Accessing nested values in nested dictionaries in Python 3.3

2024/9/20 2:50:27

I'm writing in Python 3.3.

I have a set of nested dictionaries (shown below) and am trying to search using a key at the lowest level and return each of the values that correspond to the second level.

Patients = {}
Patients['PatA'] = {'c101':'AT', 'c367':'CA', 'c542':'GA'}
Patients['PatB'] = {'c101':'AC', 'c367':'CA', 'c573':'GA'}
Patients['PatC'] = {'c101':'AT', 'c367':'CA', 'c581':'GA'}

I'm trying to use a set of 'for loops' to search pull out the value attached to the c101 key in each Pat* dictionary nested under the main Patients dictionary.

This is what I have so far:

pat = 'PatA'
mutations = Patients[pat]for Pat in Patients.values(): #iterate over the Pat* dictionariesfor mut in Pat.keys(): #iterate over the keys in the Pat* dictionariesif mut == 'c101': #when the key in a Pat* dictionary matches 'c101'print(Pat[mut].values()) #print the value attached to the 'c101' key

I get the following error, suggesting that my for loop returns each value as a string and that this can't then be used as a dictionary key to pull out the value.

Traceback (most recent call last):
File "filename", line 13, in
for mut in Pat.keys(): AttributeError: 'str' object has no attribute 'keys'

I think I'm missing something obvious to do with the dictionaries class, but I can't quite tell what it is. I've had a look through this question, but I don't think its quite what I'm asking.

Any advice would be greatly appreciated.

Answer

Patients.keys() gives you the list of keys in Patients dictionary (['PatA', 'PatC', 'PatB']) not the list of values hence the error. You can use dict.items to iterate over key: value pairs like this:

for patient, mutations in Patients.items():if 'c101' in mutations.keys():print(mutations['c101'])

To make your code working:

# Replace keys by value
for Pat in Patients.values():# Iterate over keys from Pat dictionaryfor mut in Pat.keys():if mut == 'c101':# Take value of Pat dictionary using# 'c101' as a keyprint(Pat['c101'])

If you want you can create list of mutations in simple one-liner:

[mutations['c101'] for p, mutations in Patients.items() if mutations.get('c101')]
https://en.xdnf.cn/q/119412.html

Related Q&A

scrape site with anti forgery token

Im trying to scrape data from website that uses anti forgery token what i tried to do is sending a get request then finding the key and use it to send a post request i was able to successfully scrape t…

Pandas merge and grouby

I have 2 pandas dataframes which looks like below. Data Frame 1: Section Chainage Frame R125R002 10.133 1 R125R002 10.138 2 R125R002 10.143 3 R125R002 10.148 4 R125R002 …

Find a pattern in the line of another file in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 3…

AssertionError if running code in Python prompt but not if running as file

Why trying to explain here on stackoverflow what the Python command id() does and how can it be used to reveal how Python works under the hood I had run into following strange behavior I am struggling …

Remove values before and after special character

I have a dataframe, df, where I would like to remove the values that come before the underscore _ and after the underscore _ , essentially, keeping the middle. Also keeping the digits at the end and co…

Python selection sort

Question: The code is supposed to take a file (that contains one integer value per line), print the (unsorted) integer values, sort them, and then print the sorted values.Is there anything that doesnt…

Simple inheritance issue with Django templates

just getting started in Django, and I have some problems with the inheritances. It just seems that the loop for doesnt work when inheriting other template. Heres my code in base.html:<!DOCTYPE html&…

Replacing values in a list [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Azure Release Pipeline - Environment variables on python script

Lately Ive been requested to run a python script on my Azure Release Pipeline. This script needs some environment variables for being executed, as Ive seen that in the build pipeline, the task include …

Problem with python prepared stmt parameter passing

File C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor.py, line 1149, in execute elif len(self._prepared[parameters]) != len(params): TypeError: object of ty…