Create a fresh dictionary by using a for loop to iterate through the keys of an existing dictionary

For my python programming assignment, I have a starting dictionary called aa2mw. This dictionary contains keys representing various amino acids along with their respective molecular weights. Here is what the dictionary looks like:

aa2mw = {
    'A': 89.093,  'G': 75.067,  'M': 149.211, 'S': 105.093, 'C': 121.158,
    'H': 155.155, 'N': 132.118, 'T': 119.119, 'D': 133.103, 'I': 131.173,
    'P': 115.131, 'V': 117.146, 'E': 147.129, 'K': 146.188, 'Q': 146.145,
    'W': 204.225,  'F': 165.189, 'L': 131.173, 'R': 174.201, 'Y': 181.189
    }

My task is to create a new dictionary using the same keys as aa2mw but with different values. These new values will be calculated based on a given string of arbitrary length. The calculation involves counting occurrences of each key in the string and dividing it by the length of the string.

I thought about using a loop to avoid manually typing each key into the new dictionary. However, my attempts at combining a loop with dictionary creation resulted in syntax errors. Here is my messy attempt so far:

aaCompositionDict = {key for key in aa2mw.items(): (self.inString.count(key) / len(self.inString))}

Answer №1

You are very close to the correct answer, just a slight adjustment in the syntax is needed. Consider trying this revised version:

aaCompositionDict = {key: (self.inString.count(key) / len(self.inString)) for key, _ in aa2mw.items()}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Python's Selenium for Page Object Model (POM) implementation

As a newcomer to automation testing, I am currently learning how to automate tests using Selenium with Python and the page object model. While watching tutorials on YouTube, I noticed that logging in is being done for every test case, which seems redundant ...

Tips for adjusting the voxel sizes in Matplotlib?

Looking to adjust the voxel dimensions using Matplotlib. How can I achieve this? import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.gca(projection='3d') # Create grid test2 = n ...

Changing the value of a user object's variable in Django

I have been working on implementing a feature that allows users to edit their personal information in a Django project using Django forms. However, after entering new values in the form and hitting enter, the user is redirected back to the main profile pag ...

Executing Python scripts from a shared directory

Can individuals without Python installed run a Python Selenium script as long as all dependencies are available in a shared directory? For example, if the entire Python folder and its libraries are placed in a shared directory, would users be able to exec ...

What $TERM should be utilized in order to enable both 256 colors and mouse movement events within Python's curses module?

When I set the TERM environment variable to 'xterm-1003', I can receive mouse move events, but the color display is not great and curses.can_change_color() returns False. os.environ['TERM'] = 'xterm-1003' ... curses.mousemask ...

App Engine serves up JSON data using JsonProperty

I appreciate how the JsonProperty in Python seamlessly encodes data into JSON when saving to the database and decodes it upon retrieval. However, I am seeking a solution to directly send raw JSON data to a web browser without the need for further encodin ...

Tips for accessing the time in the "2023-04-17" format from the given HTML code with Python Selenium Webdriver

<div class="medium-widget event-widget last"> <div class="shrubbery"> <h2 class="widget-title"> <span aria-hidden="true" class="icon-calendar"></span>Up ...

When attempting to automate tasks with selenium, I encountered a problem where the mouseover function was not functioning

Currently, I am working on automating a website and facing an issue while trying to access a specific submenu item by hovering over a menu. After extensive research, I found that using mouseover would be the best approach since the submenu only appears w ...

A deep dive into the nuances of DP: Unlocking the

Examining the codes below, I implemented two different approaches to solve the problem (simple recursive and DP). Why is the DP method slower? Do you have any suggestions? #!/usr/local/bin/python2.7 # encoding: utf-8 Problem Statement: An array contains ...

Dealing with large file sizes in Python with Azure Function App Blob Trigger

Currently, I am utilizing Azure function apps (Python) with a blob trigger to handle CSV processing and transferring the records to an event hub. The existing code is functional for files up to 50 rows, which was developed by following standard documentati ...

How to interact with a menu featuring an SVG tag by automating it with Selenium

I’m having trouble clicking on a menu button with Selenium on the website . None of my attempts, including using WebDriverWait, seem to work. Can someone please advise me on how I can successfully click on this button using Selenium? <div class=&quo ...

A Python list containing a variable as a reference

I have labeled my lists as layer1, layer2 ... sequentially. I am looking to utilize a variable called playerY to reference the specific numbered list when calling it. For example, if the value of playerY is 4, then I want to access the content of layer4. ...

How can a unique identifier be defined and effectively utilized for selection purposes?

I'm utilizing Selenium to automate a task on a website, and I'm facing a challenge in selecting an item using the following: select = driver.find_element_by_*whatever* Unfortunately, the available whatevers like find_element_by_id, by name, by ...

Django seems to strip out the custom html attributes I add to my option tags

I'm facing an issue with adding custom data-* attributes to the option tag within a select element. Despite using a custom template (widget) with Django, it appears that Django is somehow removing my custom attributes in later stages. Here's my ...

Discover all consecutive sequences with a cumulative value of zero

Imagine having an array containing N integers and our goal is to identify all subsequences of consecutive elements with a sum equal to zero. For example: N = 9 array = [1, -2, 4, 5, -7, -4, 8, 3, -7] The expected output should be: 1 4 4 7 5 8 1 8 ...

Gather information that is dynamic upon the selection of a "li" option using Python Selenium

I need to extract data from this website (disregard the Hebrew text). To begin, I must choose one of the options from the initial dropdown menu below: https://i.stack.imgur.com/qvIyN.png Next, click the designated button: https://i.stack.imgur.com/THb ...

What is the best way to utilize Python to solve and visualize a particular mathematical equation?

Hello, I am new to Python and have two questions that I hope you can help me solve. 1) How would I go about plotting all the points (x, y) that satisfy the following equation? y==11+(1+2x)((11x)/(5+10x))^((3y)/(3y-(5+x))) Given x>0 and y>0. 2) Now, let ...

Get the value of a JSON in template strings

After querying objects from a table, they are stored in objarr. How can I retrieve these values in the UI using JavaScript? from django.core.serializers import serialize json = serialize("json", objarr) logging.debug(type(json)) response_dict.update({ ...

Using Selenium to stream audio directly from the web browser

For my current project, I am utilizing Selenium with Python. I have been exploring the possibility of recording or live streaming audio that is playing in the browser. My goal is to use Selenium to retrieve the audio and send it to my Python application fo ...

Extract information from complex JSON structures and loop through them to create a Pandas DataFrame

Currently, I am utilizing the Foursquare API to retrieve information about venues associated with specific ZIP codes in the United States. While I have successfully obtained the JSON data, I am facing challenges in looping through and parsing it to build ...