r/pythonhelp • • Dec 13 '20

Converting Dictionary into hashable string

5 Upvotes

Hello, in trying to groupby a dataframe of New York City data by Borough, I am hit with the TypeError: unhashable type: 'dict'.

For background, I read a NYC Parks Department JSON file into Pandas that contains data on all the Parks Department big capital projects. Even though I'm sure this will be abundantly clear to you, I am very much a beginner, taking a 1.5 credit class on Python coding where my final project is using some open data source to answer a question--mine is trying to uncover any trends in completion rates and project size by NYC borough.

Below are the two different ways I tried it before realizing I needed to change the 'Boroughs' column to...not a dictionary

by_borough = df.groupby('Boroughs').size().reset_index(name='Projects')
by_borough

borough_phases = df.groupby(['CurrentPhase','Boroughs']).size().reset_index(name='Projects')
borough_phases

Key-value pairing below...

I've been researching this for over two hours and I know that I must be missing some key point of what makes a dictionary a dictionary. I just want to be able to make it mutable/hashable so that I make a df and table that looks something like this:

phases = capital_projects.groupby('CurrentPhase').size().to_frame('Projects')
phases

I don't even know how to ask this question correctly in Google, so everything I've tried to find and tried just gives me more errors. Any and all help would be so appreciated.

Thanks.


r/pythonhelp • • Dec 12 '20

[Program for School, 3.8.2] I need some kind of mathematical operation that can make it so that strings of ANY length can be made equal in length. I am new to Python and not the best at math, so help is greatly appreciated.

5 Upvotes

Variable legend:

stra = String A

strb = String B

stralen = Length of String A

strblen = Length of String B

This code is very rudimentary as my course is designed for beginners, but everything works apart from the math. How can I change the math in my code so that the two strings are the same length when appended, no matter the length of either string?

I have all strlen values printed for the sake of convenience.

### 3. Given two strings, append them together and print the result. However, if the strings are different lengths, omit characters from the longer string so it is the same length as the shorter string. So "Hello" and "Hi" yield "loHi". The strings may be any length.
###
stra = "Hello"
strb = "Wow"
stralen = len(stra)
strblen = len(strb)
print (stralen, strblen)
if stralen == strblen:
print (stra+strb)
elif stralen > strblen:
stralen = (stralen // strblen)
print (stralen, strblen)
print (stra [0:stralen]+strb)
elif stralen < strblen:
strblen = (strblen // stralen)
print (stralen, strblen)
print (stra+strb[0:strblen])


r/pythonhelp • • Dec 02 '20

Sorting TV Shows (dictionaries and lists)

5 Upvotes

I'm having issues with solving this problem with issues here and there making me even more confused on how to solve this problem. It would be great if I could see other's input so I can see where I went wrong.

Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).

Sort the dictionary by key (least to greatest) and output the results to a file named output_keys.txt. Separate multiple TV shows associated with the same key with a semicolon (;), ordering by appearance in the input file. Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt.

Ex: If the input is:

file1.txt 

and the contents of file1.txt are:

20 Gunsmoke 30 The Simpsons 10 Will & Grace 14 Dallas 20 Law & Order 12 Murder, She Wrote 

the file output_keys.txt should contain:

10: Will & Grace 12: Murder, She Wrote 14: Dallas 20: Gunsmoke; Law & Order 30: The Simpsons 

and the file output_titles.txt should contain:

Dallas Gunsmoke Law & Order Murder, She Wrote The Simpsons Will & Grace

Here's my code so far.

def readFile(filename):

dict = {}

with open(filename, 'r') as infile:

lines = infile.readlines()

for index in range(0, len(lines) - 1, 2):

if lines[index].strip()=='':continue

count = int(lines[index].strip())

name = lines[index + 1].strip()

if count in dict.keys():

name_list = dict.get(count)

name_list.append(name)

name_list.sort()

else:

dict[count] = [name]

return count

def output_keys(dict, filename):

with open(filename,'w+') as outfile:

for key in sorted(dict.keys()):

outfile.write('{}: {}\n'.format(key,';'.join(dict.get(key))))

print('{}: {}\n'.format(key,';'.join(dict.get(key))))

def output_titles(dict, filename):

titles = []

for title in dict.values():

titles.extend(title)

with open(filename,'w+') as outfile:

for title in sorted(titles):

outfile.write('{}\n'.format(title))

print(title)

def main():

filename = input()

dict = readFile(filename)

if dict is None:

print('Error: Invalid file name provided: {}'.format(filename))

return

output_filename_1 ='output_keys.txt'

output_filename_2 ='output_titles.txt'

output_keys(dict,output_filename_1)

print()

output_titles(dict,output_filename_2)

main()


r/pythonhelp • • Jun 29 '20

I am new to using python to animate, so this may be an extremely stupid question. Whenever I create an animation, this random pattern shows up. Why? And how do I fix it?

Post image
5 Upvotes

r/pythonhelp • • Feb 06 '20

I want it to say how many days old you are based on if you said you 10,11, or 12 how do I do this. When I pick an age then it says all 3 the days old. When I say I'm 10 (I'm not in real life) I want it to tell me how many days old I am instead it tells me how many days old I am for 10,11, and 12.

Post image
5 Upvotes

r/pythonhelp • • Sep 22 '26

How to make a working exe file using pyinstaller

4 Upvotes

Here is my file set up, I can't seem to get it to work no matter what.

StarDanceProject_FLStudioGrind/
├── .ruff_cache/
├── .vscode/
├── Game/
│   ├── __pycache__/
│   ├── Images/
│   ├── Maps/
│   ├── Sounds/
│   ├── BetaStats.py
│   ├── Dialogue.py
│   ├── Main.py
│   ├── Settings.py
│   ├── SOUNDS.py
│   ├── Tiles.py
│   ├── Timer.py
│   ├── UI.py
│   └── Waiver.py
├── .gitattributes
├── desktop.ini
└── README.md

r/pythonhelp • • Sep 22 '26

Subclass mysql.connector

4 Upvotes

Any idea what I am doing wrong when trying to subclass mysql.connector like this:

import mysql.connector

class Database(mysql.connector.MySQLConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

db = Database()
db_conn = db.connect(host = '...', database = '...', user = '...', passwd = '...')
print(f"{db_conn=}")

db_conn always returns None.

Edit: code above corrected to include connect() method

Edit2: Further to comment by brasticstack connect() method removed again.


r/pythonhelp • • Aug 15 '26

Professionals, please compare VS code with neovim.

4 Upvotes

Tell me the advantages and disadvantages of each.


r/pythonhelp • • Aug 14 '26

I’m looking for assistance with a github code

4 Upvotes

I got a C on my intro to python class and I can’t figure out this code

https://github.com/mcombeau/epub_downloader

Please help


r/pythonhelp • • May 24 '26

How to send a python code so that the other person can execute it without python

4 Upvotes

Hi, I'm trying to send a code to my friend to rush them happy birthday and I need the code to run in their system without them having python. The problem I'm facing rn is that she can see whatever I've written on the code and I want that bit to be a surprise that she finds out once she executes the code. How do I do this?


r/pythonhelp • • Apr 23 '26

Can I switch to Python Backend or Data Engineering after 1 year in a System Engineer role?

4 Upvotes

Hi everyone,

I graduated in 2024 with an ECE background and recently joined a startup as a System Engineer.

My current role is a mix of work:

• Around 60% technical documentation related to electronics systems

• Around 40% development work using Python, Flask, HTML, CSS, and JavaScript

However, I’m more interested in moving into pure software roles, especially Python backend development or possibly data engineering.

My questions are:

If I work here for about 1 year, will companies consider my profile for backend or data engineering roles?

Does the documentation part of my role reduce my chances when switching domains?

What skills or projects should I focus on during this year to make the transition easier?

Any advice from people who switched domains early in their careers would be really helpful.


r/pythonhelp • • Apr 08 '26

How do you avoid getting bored while learning Python?

Thumbnail reddit.com
4 Upvotes

r/pythonhelp • • Apr 06 '26

Hello, why is my code not working? Any assistance would be appreciated.

4 Upvotes
#This is a program to find the lesser of two numbers. This is a program for school and thus needs to utilize input functions

def main(a,b):
    a = int(input("Please enter the first number:"))
    b = int(input("Please enter the second number:"))

def min(a,b):
    if a>b:
        lesser = b
    else:
        lesser = a
    return lesser

main(min)def main(a,b):
    a = int(input("Please enter the first number:"))
    b = int(input("Please enter the second number:"))

def min(a,b):
    if a>b:
        lesser = b
    else:
        lesser = a
    return lesser

main(min)

r/pythonhelp • • Dec 30 '25

problem with loops

4 Upvotes

I just recently started learling python (1.5 hours into a tutorial lol), and made the collatz conjecture, and then tried the goldbach conjecture (any even number is the sum of two primes). Now I did write primes as 2k+1, which is just an oneven number, but that's not the problem.
This is the code I made

  1. number = int(input("number: "))

  2. for x in range(10):

  3. ----prime_1 = 2x + 1

  4. ----for y in range(10):

  5. --------prime_2 = 2(y+x) + 1

  6. --------sum = prime_1 + prime_2

  7. --------print(f"{prime_1} + {prime_2} = {sum}")

  8. --------if sum >= number:

  9. ------------break

  10. ----if int(sum) == int(number):

  11. --------break

  12. -

  13. print(f"{prime_1} + {prime_2}")

All the prints (except the last one) are just there so that I can see what is happening. The thing is, this code here works as I intended (except for the fact that the primes are just uneven numbers ofc), for example, if you plug in 8, it will give you 1 + 7 from line 13. But if I change the >= from line 8 to > it just gives me the biggest possible solution, so in this case 19 + 19. The break from line 9 still works as intended (atleast to me it looks like it does), but the second break doesn't work anymore (atleast I assume that is happening, and that's why I'm getting 19 + 19).

So my question is, what is going on here?


r/pythonhelp • • Dec 27 '25

Programming With Mosh or CS50p?

4 Upvotes

Hey, I’m a high schooler currently and I want to teach myself how to code. I have never coded before so I did some research and found that the one of the more useful beginner friendly languages was Python. So I’ve been researching places where I can learn.

For the most part the highest ranking options are Programming with Mosh or CS50p on YouTube. Why should I pick on or the other? Also, do you have any other suggestions? [Finally what IDE should I use because I’ve heard of VS Code but I’m also seeing things about Google Collab. I just want an IDE where I’ll be able to hopefully build projects effectively]


r/pythonhelp • • Sep 23 '25

Quick question about Python

4 Upvotes

Is Python important in full stack development in general, like for backend or databases?


r/pythonhelp • • Sep 16 '25

[macOS/Python] How to handle dependencies in a plugin system when my app is packaged as a .app?

4 Upvotes

Hey everyone,

I built a macOS menu bar app (https://github.com/Jumitti/MacMenu-qBittorrent) in Python that shows the status of my torrents (lots of features already, pretty fun project). I package it into a .app so it’s completely self-contained (all dependencies bundled, no need for users to install Python).

Recently I added a plugin system so I (or others) can add new functionality without rebuilding the whole app.

The issue:
If a plugin requires a Python package that wasn’t included at build time, it obviously won’t work, since the .app doesn’t ship with that dependency.

I’m looking for a clean way to handle this:

  • either allow plugins to install their own dependencies (maybe via an embedded pip/venv inside the app),

  • or find another best practice solution that doesn’t involve bundling hundreds of unused libraries in the main build.

Has anyone here run into this problem before? Any advice on how to design a plugin system with dynamic dependencies for a frozen Python app?

Thanks in advance 🙏


r/pythonhelp • • Jul 24 '25

Have problem with my scrapy project 😢

4 Upvotes

When I finish a simple scrapy project names apple, I enter ‘scrapy crawl apple ’,but its feedback: Scrapy 2.12.0 - no active project Unknown command: crawl … I’m confused now Thanks if you can give me any help.


r/pythonhelp • • Jun 20 '25

Is it ok to use ChatGPT when learning Python?

4 Upvotes

Whenever I’m coding and I can’t figure out how to do a certain task in Python, I always go to ChatGPT and ask it things like “how can I do this certain thing in Python” or when my code doesn’t work and can’t figure out why I ask ChatGPT what’s wrong with the code.

I make sure to understand the code it gives back to me before implementing it in my program/fixing my program, but I still feel as if it’s a bad habit.


r/pythonhelp • • Jan 27 '25

Environment Issues with DLL and Mediapipe

4 Upvotes

I am trying to run code on my machine with the latest versions of the following imports:

from psychopy.visual import Window, TextStim, Circle, Rect
from psychopy.event import waitKeys
from psychopy.core import wait
import random
import string
import math
import numpy as np
from datetime import datetime
from psychopy import gui
from pygaze.logfile import Logfile
import sys

However, it is returning this error:

File "...\Python\Python310\lib\site-packages\mediapipe\python__init__.py", line 17, in <module>

from mediapipe.python._framework_bindings import model_ckpt_util

ImportError: DLL load failed while importing _framework_bindings: A dynamic link library (DLL) initialization routine failed.

I have tried several attempts at fixing it by downloading external modules (pip install msvc-runtime), but it didn't work. Any idea on what's happening here?


r/pythonhelp • • Dec 06 '24

Github importing problem

4 Upvotes

I asked on the github subreddit but this is apparently better. Basically, I have no idea how to import across files in github. It works in thonny, but clearly github treats it a bit differently. I have the main file and the file I am importing a variable from both in the website folder but when I run the website, I get an error saying that there is no module with that name (the one I'm importing from).


r/pythonhelp • • Aug 14 '24

chatbot webssite

4 Upvotes

Hey guys! Started learning python a couple months back. Made a little chatbot as a project. it got some features like live weather updates, joke of the day and currency conversions.

i wanted to make this chatbot into an interactive website so my friends can interact with it as well. However besides a little HTML, my knowledge on web dev is poor. What should be my next steps to make it into a website? Would really appreciate all the advice and ideas

Thanks!


r/pythonhelp • • Dec 15 '23

why does 3x = 1i?

4 Upvotes

computer_list = [1,2,3,4];
user_list = [1,4,3,7];
def check_values(computer_list, user_list):
for i in range(4):
if user_list[i] == computer_list[i]:
print("red")
elif user_list[i] != computer_list[i]:
for x in range(4):
if user_list[i] == computer_list[x]:
print("white")
print(x)
print(i)

check_values(computer_list, user_list)


r/pythonhelp • • Nov 15 '23

python is hard crashing with a simple mp3 play call

4 Upvotes

The following code is hard crashing. It was working fine then suddenly something changed and I don't know what, so I created this mini test app, and it's still crashing python in the call to play. The try isn't getting caught, it's a hard crash of the python interpreter. It does correctly play the audio, then crashes before returning. Any help or guidance is appreciated, this is driving me crazy

additional info:

I've tried running from a net new virt env and the host directly

I did install the following at the host level: flac and ffmpeg

then in the virt env I've installed gtts, and pydub. there are other things installed too, but I didn't think they would be the culprit, although if I just create a virt environment with only gttsand pydub I get an error 13 calling play, whereas my other virtenv doesn't give the error 13, but I don't know what's causing that.

The error 13 is on the path: C:\Users\larry\AppData\Local\Temp\tmpm6l7dmzm.wav

even though tts.save("output.mp3") puts the output.mp3 file into the local workind folder

from gtts import gTTS               # used to convert text back to audio
from pydub import AudioSegment 
from pydub.playback import play

def text_to_speech(text):
    try:
        # Convert text to audio using gTTS and save it to a BytesIO object
        tts = gTTS(text)
        tts.save("output.mp3")

        # Load the saved MP3 file into an AudioSegment
        audio = AudioSegment.from_file("output.mp3", format="mp3")
        play(audio)   <---- hard crashing in this call



    except Exception as e:
        print (f"failed to play sound, {str(e)}")
        pass

text_to_speech("This is a test, this is only a test")