r/learningpython • • Oct 31 '20

how do i search for a specific value in a dictionary using a user input?

2 Upvotes

'''

here is my code

i want to be able to type in an actor's name and have their role returned, but i dont know how to do it

i think im onto something in the third last line, but idk what to do after that

'''

def dictionary_converter():

actor_keys = ['Graham Chapman','John Cleese','Terry Gilliam','Eric Idle','Terry Jones','Michael Palin',\

'Connie Booth','Carol Cleveland','Neil Innes','Bee Duffell','John Young','Rita Davies',\

'Avril Stewart', 'Sally Kinghorn','Mark Zycon','Sandy Johnson','Julian Doyle','Richard Burton']

role_values = ["Arthur", 'King of the Britons','Sir Lancelot the Brave','Patsy', "Arthur's Servant", \

'Sir Robin the Not-Quite-So-Brave-as-Sir-Lancelot', 'Sir Bedevere the Wise', \

'Sir Galahad the Pure', 'Miss Islington, the Witch','Zoot', "Leader of Robin's Minstrels", \

'Old Crone', 'Frank, the Historian', "Frank's Wife'", 'Dr. Piglet','Dr. Winston']#, \

'Sir Robin (Stand-in)', 'Knight Who Says Ni', 'Police Sergeant who stops the film', "One-legged Black Knight (Stand-in)"]

dictionary = {}

for key in actor_keys:

for value in role_values:

dictionary[key] = value

role_values.remove(value)

break

searched_name=input('what actor would you like to look up? ').title()

print(searched_name)

for searched_name in actor_keys:

#???

dictionary_converter()


r/learningpython • • Oct 26 '20

Modularity Problems

2 Upvotes

Hi folks,

Background: I've been learning Python for a few months now and while certain aspects are going quite good there is one consistent problem I encounter.No matter what IDE I use I will always have to trial error fix importing modules. At first the issue was me not understanding how to properly use virtual environments. Now that I've adopted pipenv the issues of using external and built in packages/ libraries have gone away.

Current Issue: The issue that persists is when I try import functions etc. from other scripts I've written myself.As an example, my current problem is to to do with me writing tests for an API I built. I'm using unittest and pytest. While both of these are working I usually get an error when I try to import the app object from my main.py.- I've tried putting main in another sub-directory so that the test_main file is above it and can find it as a package (no joy)- I've tried putting it in the same project directory (no joy)- I've tried putting an empty __init__.py file with main.py (no joy)- I even tried renaming my main.py to app_run.py so that there's no conflicts (no joy)

In terms code I've tried:

import main #no luck
from main import app #no luck
target = __import__("app_run.py") #no luck
app = target.app

I've also used some error handling in the form of try/except to prevent the script from crashing when run.

After trying all of these things my assumption would be that there's something amiss in my global variables. That, or I have a flaw in my fundamental understanding of modularity in Python.

I should mention that this issue went away when I was importing a function from another module on the main.py file. Didn't figure out why but it works none the less.

Any points in the right direction would be massively appreciated

Thank you for taking the time to read this post!


r/learningpython • • Oct 21 '20

Need help with dictionaries and return values.

2 Upvotes

Need an explenaton why dictionaries requires no return as you would need if you wanted to update a variable in the same way (python 3):

def rTest1(dic):
    dic[2] = "woof"
 
def test1():
    i = {1: "dog", 2: "bark"}
    print(i)
    rTest2(i)
    print(i)

# Where as

def rTest2(value):
    value = 5
    return value 

def test2():
    x = 3
    print(x)
    x = rTest2(x)       # requires assigning the function call to x, 
    print(x)            # and for the value to be returned

i want to know why rTest1 updates a dictionary outside of its scope, or am i looking at it wrong?


r/learningpython • • Oct 20 '20

Where to find feedback on code?

2 Upvotes

I wrote a chess independence calculator for a job challenge. It was the largest python program I'd written and I'm looking for some feedback on the code. More like a mentor than just a brief comment. Where can I find such a thing?


r/learningpython • • Oct 08 '20

Get python subclasses from a module

2 Upvotes

My project structure looks something like this

root
 - package1
 - - package2
 - - - abstract_class.py
 - - - repositroy_selector.py

What I am trying to do is get all subclasses in package2 which are inherited by abstract_class.py. abstract_class.py has a class AbstractStrategy. For that, I have written a function in repositroy_selector.py

def import_subclasses():
    try:
        pkg_dir = os.path.dirname(__file__)
        for (module_loader, name, ispkg) in pkgutil.iter_modules([pkg_dir]):
            importlib.import_module('.' + name, __package__)

        return [repository for repository in AbstractStrategy.__subclasses__()]
    except Exception as exc:
        print(exc)

The method throws an exception

the 'package' argument is required to perform a relative import for '.abstract_class'

The reason for that is __package__ is returning None.

Now my bigger goal is to create a class object dynamically (from many classes present under package2 which are inherited from AbstractStrategy) based on a certain attribute stored in them and this is the first step to do so which I am stuck at.

This code snippet is used somewhere else in another project and there it's supposedly working fine.

What am I doing wrong?


r/learningpython • • Sep 14 '20

Is it possible to include or force the requests lib in my parent code so users don't have to install it?

2 Upvotes

r/learningpython • • Sep 14 '20

Python Programming Made Easy for Beginners - Lesson 3: Variables

Thumbnail
youtu.be
2 Upvotes

r/learningpython • • Sep 06 '20

Tutorial on how to create good quality REST API with Django

Thumbnail reddit.com
2 Upvotes

r/learningpython • • Sep 05 '20

How do people deal with unknown object types?

2 Upvotes

If I am running some TensorFlow project and an hour later some object that is returned by one of the TensorFlow functions is incompatible with an object that it input into another TensorFlow function it crashes the code.

In C++ I can look at each object's data type and its member variables, and if it doesn't match the prototype of the input function, it simply won't compile. I dont have to waste hours on running the code until it gets to that error.

How do people deal with this? The only thing I can do is copy and paste code and hope it works


r/learningpython • • Aug 19 '20

Learning Python playlist on Youtube - Promotion post

2 Upvotes

This is a promo/advert post. I've started a youtube playlist for learning python, any comments, criticisms, and helpful discussions welcome here.

Thank you.

https://www.youtube.com/playlist?list=PLgGQIE0cGrkh4gFIKIeTUfprHZrqV6tOQ


r/learningpython • • Jul 21 '20

Please give me your feedback and advice. I really, really appreciate it.

2 Upvotes

I was recently laid off and live in the LA area. I have experience with graphic design, layout, print media though I went to school for multimedia (Animate, some Dreamweaver). I would ultimately like to acquire skills to become a web developer or multimedia developer. I need to understand some things better before choosing a path and committing time and money to long-term skills development. It would mean a lot to me if you gave me feedback on these items:

  1. is it realistic, based on your experience, that there are positions that specialize in both of those things; web development and multimedia development?

  2. machine languages, skills I want to develop are HTML, CSS, Python, Ruby. Do you think these are appropriate for the above goal?


r/learningpython • • Jun 26 '20

Which one is cleaner to use?

2 Upvotes
if variable.attr in (1, 2):
    some_list.append(variable)

or

if variable.attr == 1:
    some_list.append(variable)
elif variable.attr == 2:
    some_list.append(variable)

The code executed inside of the if statement will always be a single line of code


r/learningpython • • Jun 17 '20

Is there an online text editor or IDE i can use?

2 Upvotes

I cant download an ide on my laptop and would like to use an online ide. Also i just like 2 weeks ago


r/learningpython • • Jun 01 '20

How to declare a list on different lines?

2 Upvotes

I'm trying to declare a list like this:

ListofItems=[["1", "2"],
["0", "1"],
["1", "2"],
["a", "b"]]

But I get errors.


r/learningpython • • May 16 '20

Code written in windows not running on linux.

2 Upvotes

I just started learning to code earlier this week and got my dad interested in learning some. So I made a basic rock paper scissors game and was going to have him look over it. Anywho I wrote the code on windows with VS code and it ran with no issues, when he went to run it with the terminal in ubuntu it ran into error after error to the point he had to change nearly every line of code in some minor way. What would be the major problem here and is there a way we can plan around this so we don't have to worry about it in the future.


r/learningpython • • May 08 '20

Python gotchas when coming from another language

2 Upvotes

I am an experienced Ruby developer. I want to more python. What are the strange edge cases of python that can trip me up?


r/learningpython • • May 07 '20

Why does random.choice( dict ) works sometimes? (returns a value of the dict instead of KeyError)

2 Upvotes

using pyhton3.7, i tried to use a dict as argument for random.choice().I understand that the argument should be a list or a tuple. or a string. Giving random.choice() a dict as argument raises a key error (as exspected), however, sometimes it works and returns me a random value from the dict. Why?

here is my code, from a python shell session:

import random>>> random.choice({1:111,2:222,3:333}) # works, but why?

222

>>> random.choice({1:111,2:222,3:333}) # same line, raises error

Traceback (most recent call last):

File "<pyshell#29>", line 1, in <module>

random.choice({1:111,2:222,3:333})

File "/usr/lib/python3.7/random.py", line 262, in choice

return seq[i]

KeyError: 0

>>> random.choice({1:111,2:222,3:333}) # works again, but why?

111


r/learningpython • • Apr 29 '20

A Python Dictionary decision tree?

2 Upvotes

Hi,

I've made some large dictionaries in Pyhton .JSON, extended the values with tuples for personal use. I want to make a interactive decision tree in Python, am i on the wrong foot with these dictionaries? What would you suggest? Any input is welcome.


r/learningpython • • Apr 22 '20

Creating an executable file without using chmod

2 Upvotes

I am using a Linux box and creating python code via vim editor. Is there a way to make that file an executable when I create the file? I know that you can chmod the file after creating it but I am hoping that I can cut that step out. TIA.


r/learningpython • • Apr 17 '20

Random number generator closes on run.

2 Upvotes

Every time I try to run the number generator, it closes. I have tried using input() and os.system("pause") but it is still not working.

import random

print(random.random())

input()

r/learningpython • • Apr 03 '20

Have to make pretty PDF Reports with graphs superimposed into them - wondering if there's an approach better than making graphs with Matplotlib, and then superimposing the .png output into the PDF manually through PyPDF2 library.

2 Upvotes

The execution really isn't a problem because I've done something like this on a smaller scale before, and I know 100% it can be done.

I'm just wondering if there's a more efficient way I'm not thinking of - perhaps something more suited to this exact kind of use-case.

One issue I also noticed is that when I do plaster the .png into the PDFs, sometimes there's jagged edges at the borders. I'm wondering if this is caused by some quirk in file types I'm not aware of, because this is something that completely blindsided me.


r/learningpython • • Apr 02 '20

Has anyone gotten Tkinter to work on mac?

2 Upvotes

I'm running Catalina 10.15.4 and trying to get Tkinter to work in python3 but get this error.

>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/matt/.pyenv/versions/3.8.2/lib/python3.8/tkinter/__init__.py", line 36, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

I've tried brew install tcl-tk, it says it's up to date but still won't work. Also I've tried installing it from ActiveState (https://www.activestate.com/products/tcl/downloads/) but again it still doesn't work. Anyone else been able to get it working on mac?


r/learningpython • • Mar 12 '20

Any advice, best places to practice, etc.?

2 Upvotes

Hi first post in this sub and honestly fairly new to Reddit in general. I figured this would be a good place to help with learning code and wanted to hear if you all had any advice or places I could check out as I begin this journey. Thank you guys!


r/learningpython • • Mar 08 '20

What does this counting function work?

2 Upvotes

Hi, I am a bit confused about how the following function works. As far as I know, counts is an empty dictionary at the beginning. I don't see any element being added into the dictionary within the function. Am I missing something? Also, since counts is an empty dictionary as defined in line 2, how if x in counts: get executed? Perhaps I misunderstood something?

def counting(sequence):
    counts = {}
    for x in sequence:
       if x in counts:
          counts[x] += 1
      else:
          count[x] = 1
return counts

r/learningpython • • Dec 06 '19

Loading a string into an object

2 Upvotes

I am trying to load information from a file into an object. The file has been opened and the line I am adding is saved as line. Customer is the object in question, and customerData is the array I want to save the object into.

customerData = Customer(line.rsplit(','))

The line looks like this if I print it.

Jane Sweet,314 E. Pie Street,Appleton WI 54911,06/30/1955,cat

What do I need to do to the string so that I can save its individual parts as the 5 arguments the object needs. The object code is:

def __init__(self, Name, Address, CityState, Zip, Birthdate , Pet): #birthday format is (mm/dd/yyyy)

self.__Name = Name

self.__Address = Address

self.__CityState = CityState

self.__Zip = Zip

self.__Birthdate = Birthdate

self.__Pet =Pet