Declaring a new variable with a string name - python

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"]

Related

Problems with using a for loop with a string from a text file to locate an index in a list of lists

I have a text file with a string that has a letter (beginning with "A" that is assigned to a random country). I import that line from the text file to be used with my code where I have a list of countries and rates. I strip the string so that I am left with the country and then I want to be able to locate the country in the string on a list of list that I created. The problem is that when I run my for loop to find the name of the country in the string in the list of lists, where each junior list has the name of the country, GDP and a rate, the for loop runs and can't find the country in the string, even though they are the same type and same spelling. Let me post my code and output below.
When I created the txt file or csv file, this is what I used:
f = open("otrasvariables2020.txt", "w")
f.write(str(mis_letras_paises) + "\n")
f.write(str(mis_paises) + "\n") #(This is the string I need)
f.write(str(mis_poblaciones) + "\n")
f.close() #to be ready to use it later
Let me post some of the output.
import linecache
with open("otrasvariables2020.txt") as otras_variables:
mis_paises = (linecache.getline("otrasvariables2020.txt",2))
#Here I get the line of text I need, I clean the string and create a
#list with 5 countries.
lista_mis_paises = mis_paises.translate({ord(i): None for i \
in "[]-\'"}).split(", ")
for i in lista_mis_paises:
if "\n" in i:
print(i)
i.replace("\n", "")
for i in lista_mis_paises:
if len(i) <= 2:
lista_mis_paises.pop(lista_mis_paises.index(i))
Final part of the question: So, ultimately what I want is to find in the array the junior list of the country in the list/string I imported from the text file. Once I locate that junior list I can use the rates and other values there for calculations I need to do. Any ideas what's wrong? The outcome should be the following: Afganistán and other 4 countries should be found in the list of lists, which, for Afganistán, happens to be the 1st item, so I should now be able to create another list of lists but with just the 5 countries instead of the 185 countries I began with.
If the concern you have is to strip special characters you don't want to use, I'll do something like that:
countries = linecache.getline("otrasvariables2020.txt",2).strip('[]-\'"').rstrip('\n').split(', ')
Note: with open("otrasvariables2020.txt") as otras_variables: is not used in the code you shared above, so can be removed.
Hope it helps.

How does Python go about reading over lines in a .txt file and split them into a list?

So I am having trouble understanding how Python creates lists using the .split() string method if I were to give it a file to read.
Here I have a text file with populations from three different countries called population.txt:
United-States 325700000
Canada 37000000
China 13860000000
and in another .py file, I have this code:
populationFile = open("population.txt", 'r')
for populationLine in populationFile:
populationList = populationLine.split()
print(populationList)
populationFile.close()
The output is this:
['China', '13860000000']
Does python essentially put each country and the respective population in separate lists by reading each line as it did with China, or is it by character?
Also, how come only one list appears here and not all of them?
Sorry for all the questions, but I will be very grateful for anyone who can help :)
What you are doing is setting the value for populationList on top of the previous iteration. so it is splitting the United States population, then splitting the Canada population and saving it over the United States, then China replaced Canada.
What you can do it append;
populationFile = open("population.txt", 'r')
populationList = [] # create an empty list
for populationLine in populationFile:
populationList.append(populationLine.split()) # append the split string into list
print(populationList)
populationFile.close()
If you would like to optimize this, you can use a with block. It would look like this:
with open("population.txt", 'r') as populationFile:
populationList = [] # create an empty list
for populationLine in populationFile:
populationList.append(populationLine.split())
print(populationList)
This only opens the file temporarily and when the with block is complete, it closes it automatically.
how come only one list appears here and not all of them?
populationList is changing after each iteration and losing (by overwriting) its earlier value.
Instead you should try this:
for populationLine in populationFile:
populationList.append(populationLine.split())
You need to change your code to this
populationFile = open("population.txt", 'r')
temp = None
# create an empty list
populationList = []
for line in populationFile:
# split into different words by the space ' ' character
temp = line.split() # temp = ['Canada', '37000000'] or ['China', '13860000000']
# if spaces exist on either the right or left of any the elements in the temp list
# remove them
temp = [item.strip() for item in temp[:]]
# append temp to the population list
populationList.append(temp)
print(populationList)
populationFile.close()

How do I change values in a dictionary in one key?

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

retrieving name from number ID

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.

Python Searching and removing an item plus the following two from a text file

I am just starting out with programming and am learning Python. I am having some troubles searching and removing from a text file. The text file contains a list of single spaced names. I need to have the user input a name and have it and the two following items removed from list.
Right now I am able to find and remove the searched for name and write the new list to the text file but I can't figure out how to remove the next two items. I tried using list.index to get the position of the searched for name but it gives the location of the first letter in the name. Is there a way that I can search the input word and get the location of the whole word ('bob','tom','jill') (0,1,2) and use this to do what I need done?
Thanks.
Assuming the contacts file is three lines per contact, an example file might look like this:
Fred
58993884
AnyTown
Mary
61963888
SomeCity
Bill
78493883
OtherTown
Anne
58273854
AnyCity
Script:
x = raw_input('Enter Name of Contact to Delete: ')
# do a case-insensitive match for names
target = x.strip().lower()
# create a list of all valid contacts
skip = False
contacts = []
with open('contacts.txt', 'r') as stream:
for index, line in enumerate(stream):
# check every third line
if not index % 3:
skip = (line.strip().lower() == target)
if skip:
print 'Removed Contact:', line
if not skip:
contacts.append(line)
# re-open the contacts file for writing
with open('contacts.txt', 'w') as stream:
stream.write(''.join(contacts))
Output:
$ python2 /home/baz/code/misc/test.py
Enter Name of Contact to Delete: Mary
Removed Contact: Mary
$ cat contacts.txt
Fred
58993884
AnyTown
Bill
78493883
OtherTown
Anne
58273854
AnyCity
Instead of manipulating the list string of the names it would be better to manipulate a list of string names. You can easily convert the "big string" into a list using string.split:
names_string = 'john robert jimmy'
names_list = names_string.split(' ') # names_list = ['john', 'robert', 'jimmy']
Now, you can easily add, remove or search names in this list, using basic list functions:
names_list.append('michael') # names_list = ['john', 'robert', 'jimmy', 'michael']
names_list.remove('robert') # names_list = ['john', 'jimmy', 'michael']
jimmy_position = names_list.index('jimmy') # jimmy_position = 1
Remember handling the exceptions when the element is not in the list.
To convert the list of names into a "big string" again, you can use string.join:
names_string = ' '.join(names_list)

Categories

Resources