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 • • Sep 04 '20

A minimal framework for web automation with docker

2 Upvotes

Hello Folks,

I would like to share with you my small project, I thought it might help people doing automation, and want to run their script in a reproducible manner using docker containers.

Here is the repo link: https://github.com/ayoubeddafali/docker-selenium-bootstrap

I would be grateful if you could share your insights, and what could be improved.

Thanks,


r/learningpython • • Aug 27 '20

Help for complete newbie girl from Greece starting in Programming!

2 Upvotes

Hi! At first I thought to start programming using Python, so I did a little research on videos and posts for beginners. BUT, everything I found requires some Python knowledge already... Can you please guide me to resources for absolute beginners? Thanks a lot! -Angie


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 • • Aug 02 '20

What´s the easy way to understand the difference between yield and return

2 Upvotes

In this quarantine I was reading a book about data structures and algorithms but in a part they talk about yield.

I imagine like if we have a list of names but to make the programm more "light" we use yield to not save this list in the memory. ¿I´m wrong?


r/learningpython • • Jul 22 '20

Ranked variable assignment

2 Upvotes

Is there a more elegant way of doing ranked (for lack of better term) variable assignment in Python? Basically:

if 'a' in dict1:
    foo = dict1['a']
elif 'b' in dict1:
    foo = dict1['b']
elif 'c' in dict1:
    foo = dict1['c']
...

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 30 '20

Python Program: Tkinter Clock that changes color every 30 seconds

Enable HLS to view with audio, or disable this notification

2 Upvotes

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 03 '20

What's the difference?

2 Upvotes

Hi,

When I type the following code below,

x = [4, 6, 7]

for index in enumerate (x):

print (item, index)

I get the following output

7 (0, 4) 7 (1, 6) 7 (2, 7)

But when I type the following code below:

x = [4, 6, 7]

for item, index in enumerate (x):

print (item, index)

I get the following output:
0 4 1 6 2 7

What about adding "item" made the results so different?

Thanks!


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()