For example, I have a key = name. Within name, there's birthday, age, and phone number. I would only like to change say birthday but keep the rest. And I'm trying to use an existing file that have the names already.
So if you want to use a tuple as a key the syntax would be
d[(name, phoneNumber)] = birthday
as far as using values in a pre-existing file you will need the open method.
file = open("fileName.csv",r) # assuming that you have a file of comma separated values
text = file.read()
.split("\n")
peps = [p.split(",") for p in text]
dictionary = {}
for p in peps:
d[(p[column of name] , p[col# for phone number)]]=p[#Bday]
Roughly. There are several types of collections in python, {}, [], (), hash and set. I would recommend that you read up on each here
Related
I am trying to create a "This is Your New Name Generator" program. I am doing this by asking the user for their first and last name. The program then takes the first letter of their first name, and the last letter of the their last name, and pulls from two text files to give their new first and last name.
I've gotten as far as getting the user's first and last name, and pulling information from a file, however it always gives me the last line of the file.
I thought I could setup the files like dictionaries and then use the user's input as keys, but it doesn't seem to be working.
Any advice?
firstName = input("What is your first Name? ")
lastName = input("What is your last Name? ")
fN = firstName[0].lower()
lN_len = len(lastName) -1
lN = lastName[lN_len]
fNdict = {}
with open('firstName.txt') as f:
for line in f:
(fN, fNval) = line.split(",")
fNdict[fN] = fNval
lNdict = {}
with open('lastName.txt') as fileobj:
for line in fileobj:
lNkey, lNvalue = line.split(",")
lNdict[lN] = lNvalue
newFirstName = fNval
newLastName = lNvalue
print("Your zombie Name is: %s %s "%(newFirstName,newLastName))
Reference Image:
When you run these lines:
newFirstName = fNval
newLastName = lNvalue
fNval and lNvalue have the last values they had in their respective loops. I think you mean to use the user's first and last names as keys to the dictionaries, e.g.
newFirstName = fNdict[fN]
newLastName = lNdict[lN]
Note that this will fail if fN and lN aren't in the dictionaries. You might want to create defaultdicts instead.
Note also that Python has an official style guide that most Python developers follow. Please consider reading it and writing your code accordingly. The code you've shared is very hard to read.
You could follow a slightly different implementation to achieve the same result.
Create two python dictionaries with all the associations letters - first names and letter - last names.
Write them in a file using json. This file will substitute yours firstName.txt and lastName.txt
This should be done only once to create the file with the names.
Then your name generator is a script which:
Loads those two dictionaries.
Ask the user for an input to obtain the keys.
Retrieve the names from the dictionaries using the user input.
The first two points are implemented in this way:
import json
#these are just brief examples, provide complete dictionaries.
firstnames = {"A": "Crafty", "B": "Brainy"}
lastnames = {"A": "Decapitator", "B": "McBrains"}
with open("fullnames.txt", "w") as ff:
json.dump(firstnames, ff)
ff.write('\n')
json.dump(lastnames, ff)
This would be a script to generate the file with the names.
The name generator would be:
import json
with open("fullnames.txt", "r") as ff:
ll = ff.readlines()
firstnames = json.loads(ll[0].strip())
lastnames = json.loads(ll[1].strip())
inputfirst = input("What is your first Name? ")
inputlast = input("What is your last Name? ")
fn = inputfirst[0].upper()
ln = inputlast[-1].upper() #negative indexes start from the last element of the iterable, so -1 would be the last.
print("Your zombie Name is: {} {} ".format(firstnames[fn], lastnames[ln])) #using string format method, better that the old %
so I am trying to write a function that will read a text file, extract the information it needs from a line of text, and then assign that information to a key in a python dictionary. However here is a problem i have.
def read_star_names(filename):
"""
Given the name of a file containing a star catalog in CSV format, produces a dictionary
where the keys are the names of the stars and the values are Henry Draper numbers as integers.
If a star has more than one name, each name will appear as a key
in the dictionary. If a star does not have a name it will not be
represented in this dictionary.
example return: {456: 'BETA', 123: 'ALPHA', 789: 'GAMMA;LITTLE STAR'}
"""
result_name = {}
starfile = open(filename, 'r')
for dataline in starfile:
items = dataline.strip().split(',')
draper = int(items[3])
name = str(items[6])
result_name[name] = draper
starfile.close()
return result_name
This is attempting to read this:
0.35,0.45,0,123,2.01,100,ALPHA
-0.15,0.25,0,456,3.2,101,BETA
0.25,-0.1,0,789,4.3,102,GAMMA;LITTLE STAR
The problem I am having is that what it returns is this:
{'ALPHA': 123, 'GAMMA;LITTLE STAR': 789, 'BETA': 456}
I want the GAMMA and the LITTLE STAR, to be seperate keys, but still refer to the same number, 789.
How should I proceed?
I tried splitting the line of text at the semicolon but then that added indexes and I had a hard time managing them.
Thanks.
You already have isolated the part that contains all the names, all you need to do is separate the names and make separate keys for each of them, as so
for i in name.split(";"):
result_name[i] = draper
I have this code that iterates a text file, and each line will contain a companys name. I then want the loop to make a list with the name of that specific line.
So let's say I have a file with: Volvo, Audi, BMW
Then the program will do something like the following:
for line in textfile:
line = []
So now I should have three empty lists: Volvo, Audi and BMW.
I'm sorry if this was confusing, what I'm really trying to ask is,
is it possible to initialize a variable with a string name?
lets say I have a string car = "volvo". Can I make a new variable, for example a list, with the name of the car object?
What you need is a dictionary, so you can do:
my_companies = {}
for line in textfile:
my_companies[line] = []
Now you can access your lists by the company names of a single dictionary
examples:
print my_companies["Volvo"]
print my_companies["Audi"]
print my_companies["BMW"]
I have a code that takes data from online where items are referred to by a number ID, compared data about those items, and builds a list of item ID numbers based on some criteria. What I'm struggling with is taking this list of numbers and turning it into a list of names. I have a text file with the numbers and corresponding names but am having trouble using it because it contains multi-word names and retains the \n at the end of each line when i try to parse the file in any way with python. the text file looks like this:
number name\n
14 apple\n
27 anjou pear\n
36 asian pear\n
7645 langsat\n
I have tried split(), as well as replacing the white space between with several difference things to no avail. I asked a question earlier which yielded a lot of progress but still didn't quite work. The two methods that were suggested were:
d = dict()
f=open('file.txt', 'r')
for line in f:
number, name = line.split(None,1)
d[number] = name
this almost worked but still left me with the \n so if I call d['14'] i get 'apple\n'. The other method was:
import re
f=open('file.txt', 'r')
fr=f.read()
r=re.findall("(\w+)\s+(.+)", fr)
this seemed to have gotten rid of the \n at the end of every name but leaves me with the problem of having a tuple with each number-name combo being a single entry so if i were to say r[1] i would get ('14', 'apple'). I really don't want to delete each new line command by hand on all ~8400 entries...
Any recommendations on how to get the corresponding name given a number from a file like this?
In your first method change the line ttn[number] = name to ttn[number] = name[:-1]. This simply strips off the last character, and should remove your \n.
names = {}
with open("id_file.txt") as inf:
header = next(inf, '') # skip header row
for line in inf:
id, name = line.split(None, 1)
names[int(id)] = name.strip()
names[27] # => 'anjou pear'
Use this to modify your first approach:
raw_dict = dict()
cleaned_dict = dict()
Assuming you've imported file to dictionary:
raw_dict = {14:"apple\n",27:"anjou pear\n",36 :"asian pear\n" ,7645:"langsat\n"}
for keys in raw_dict:
cleaned_dict[keys] = raw_dict[keys][:len(raw_dict[keys])-1]
So now, cleaned_dict is equal to:
{27: 'anjou pear', 36: 'asian pear', 7645: 'langsat', 14: 'apple'}
*Edited to add first sentence.
I want to have some variables that are stored in a file (text file or yaml file)
for example if I have these variables stored in the file
employee = ['Tom', 'Bob','Anny']
salary = 200
managers = ['Saly','Alice']
and I want the user to enter the list name or the variable name for example
if the user entered employee and want to do some operations on the list values so the user supposed to access employee[0], employee[1] .... etc
how can I write a python script that will go to the file search for the correct variable and give the user access to its value
Thanks
Like what #Levon said, there are several ways that allow you do that, and the best depends on your problem context. for example, you could
read the file yourself by formatting it e.g., via delimiter "=" in your file
use a database to store your data
use pickle or shelve to serialize your variables and get them back later.
put the variables in a python module and import it
This approach might be one way assuming your file contents is somewhat consistent:
Updated: I added the code necessary to parse the lists which previously wasn't provided.
The code takes all of the data in your file and assigns it to the variables as appropriate types (i.e., float and lists). The list parsing isn't particularly pretty, but it is functional.
import re
with open('data.txt') as inf:
salary = 0
for line in inf:
line = line.split('=')
line[0] = line[0].strip()
if line[0] == 'employee':
employee = re.sub(r'[]\[\' ]','', line[1].strip()).split(',')
elif line[0] == 'salary':
salary = float(line[1])
elif line[0] == 'managers':
managers = re.sub(r'[]\[\' ]','', line[1].strip()).split(',')
print employee
print salary
print managers
yields:
['Tom', 'Bob', 'Anny']
200.0
['Saly', 'Alice']