Python - CSV Reading with dictionary [duplicate] - python

This question already has answers here:
TypeError: 'dict_keys' object does not support indexing
(5 answers)
Closed 7 years ago.
So,
I am using Python 3.4.2 and I have this code:
import csv
import random
filename = input("Please enter the name of your file: ")
# Open file and read rows 0 and 1 into dictionary.
capital_of = dict(csv.reader(open(filename)))
# Randomly select a country from the dictionary
choice = random.choice(capital_of.keys())
# The correct capital corresponds to the dictionary entry for the country
answer = capital_of[choice]
# Take a guess from the user
guess = input("What is the capital of %s? " % choice)
# If it's right, let the user know
if guess == answer:
print("Right-o!")
# Otherwise, do what you want to do.
This code was given to me as a solution on a previous question but upon entering the name of my CSV file, I get this error:
TypeError: 'dict_keys' object does not support indexing
Does anybody know a fix for this?
Thanks

Try this:
choice = random.choice(list(capital_of.keys()))

Related

How to ask the user again if he wants to remove more links in my python code [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
Hi I have a python code which does the following things sequentially
Displays a list of urls
asks the user if they want to remove
any links.
If the user inputs yes then takes an input which link
to remove and removes the link
code exits.
My issue is I want the code to ask the user again after removing the link if they want to remove more links?
Can someone help me figure it out. Sorry I am new to python so if this question seems very trivial.
My code:
import sys
def remove_links():
# initializing list
list = links
# initializing string
str_to_remove = input("Enter the link you want to remove: ")
# Remove List elements containing String character
# Using list comprehension
links.remove(str_to_remove)
# printing result
print("The list after removal : " + str(links))
print(len(links))
# printing original list
print("The list of links are : " + str(links))
print(len(links))
# Sets to simplify if/else in determining correct answers.
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
# Convert their input to lowercase.
choice = input("Do you want to remove some/any links? (y/N) ").lower()
if choice in yesChoice:
remove_links()
elif choice in noChoice:
# exit the code
sys.exit("User doesn't want to make any modifications.")
else:
# print("Invalid input.\nExiting.")
sys.exit("Invalid input.\nExiting.")
You can put it in while loop, like this and reaplace sys.exit() to break:
while True:
choice = input("Do you want to remove some/any links? (y/N)").lower()
if choice in yesChoice:
remove_links()
elif choice in noChoice:
print("User doesn't want to make any modifications.")
break
else:
print("Invalid input.\nExiting.")
break
This is only one way to do this

Error is being shown when I run the code and I am unable to figure out the second question

import pickle
med = {}
medfile = open("Medicines.dat","wb")
while True:
name = input("Enter the name: ")
company = input("Enter the company: ")
chemical = input("Enter the chemical: ")
price = input("Enter the price: ")
med['name'] = name
med['company'] = company
med['chemical'] = chemical
med['price'] = price
pickle.dump(med,medfile)
ans = input("Wouldyou like to add more(y/n) ")
if ans == "y":
continue
elif ans == "n":
break
medfile = open("Medicines.dat","r+")
print(pickle.load(medfile))
medfile.close()
The question is as follows:
A binary file "Medicines.dat has structure [Name, Company, Chemical, Price] a) Write a user defined function add_data() to input the data for a record and store in the file b) Write a function search() which accepts a company name and displays the details of all the Medicines by that company
There are a few problems here:
1st Opening the file correctly
medfile = open("Medicines.dat","r+")
You mean rb. The difference is explained here, but pickle parsing requires the file to be in "binary" mode, hence the "b".
2nd Closing the file correctly
You should close the file before re-opening it for writing, as a matter of best practce. (medfile.close()). Even better, python will take care of when the file gets closed if you use the "with" syntax to create a context
3rd Having the right values
While the code should now run, I doubt it will do what you want. Your query asks "Wouldyou [sic] like to add more(y/n)", but it does not look to me like it is adding more values, since you use the same "med" dictionary over and over. Consider how the "new" fields would ever be distinguishable from the "old" ones, based on their key

Enter value to produce keys in dictionary [Python] [duplicate]

This question already has answers here:
Reverse / invert a dictionary mapping
(32 answers)
Closed 6 years ago.
I have made my own Morse Code translator where you can enter the code and the corresponding letter prints out. However, what I want to do is that whenever I enter a letter, the code prints out. Here's my code:
MorseCode = {'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z',
'.----':1,
'..---':2,
'...--':3,
'....-':4,
'.....':5,
'-....':6,
'--...':7,
'---..':8,
'----.':9,
'-----':0
}
print "Type 'help' for the morse code."
print "Type 'end' to exit the program.\n"
while True:
code = raw_input("Enter code:")
if code in MorseCode:
print MorseCode[code]
So the question is: Is there a way to somehow invert this dictionary so whenever I enter 'A', '.-' will print out? I'm only studying python for two weeks now so I'm still mastering the basics before I move on to the more advanced levels. Thank you!
You can use dictionary comprehension (assuming you are using Python 2.6+) to easily create a new, inverted dictionary:
letters_to_morse = {char: code for code, char in MorseCode.items()}
letters_to_morse['A']
>> '.-'

How to catch a character from keyboard [duplicate]

This question already has answers here:
How to read keyboard input?
(5 answers)
Closed 6 years ago.
I am working on a python project and I have got the following questions.
How to catch a character in python ? What modules I need to use ? What functions I need to use?
If you need to take a line of input just use:
x = input('Your name: ')
y = input()
Or (For Python 2)
x = raw_input('Your name: ')
y = raw_input()
For taking just one character from the keyboard you can use msvcrt.getch():
import msvcrt
key = msvcrt.getch()
if key == 'a':
print("You pressed a")

Python - Can users call variables with only part of its name? [duplicate]

This question already has answers here:
Dynamic variable in Python [duplicate]
(2 answers)
Closed 8 years ago.
What im trying to do is have the user type a number, which would then register into the system as a specific variable.
Example:
n1 = "X"
n2 = "Y"
n3 = "Z"
num = input("enter a number (1-3): ")
print(n(num))
So, if the user entered the number 2 into their program, the program would display the value stored in n2, or be able to use n2 in an equasion.
Is this possible? I'm still new to Python and this is not a school assignment, just my own curiosity :)
Thanks
EDIT:
Here is what im trying to do:
temp = int(input("\nPlayer One, please pick a square (1-9): "))
while {1:n1, 2:n2, 3:n3, 4:n4, 5:n5, 6:n6, 7:n7, 8:n8, 9:n9}[temp] == "X" or {1:n1, 2:n2, 3:n3, 4:n4, 5:n5, 6:n6, 7:n7, 8:n8, 9:n9}[temp] == "O":
temp = str(input("\nPlayer One, please pick a valid square (1-9): "));
{1:n1, 2:n2, 3:n3, 4:n4, 5:n5, 6:n6, 7:n7, 8:n8, 9:n9}[temp] = "X"
You could use a dictionary for this. Like:
num = input("...")
print {1:n1, 2:n2, 3:n3}[num]
Hope that helps.

Categories