How to access the value of every single row pandas dictionary - python

I create a dictionary from a dataset and now I want to access every single row of the dictionary. Every single row of this dictionary contains 2 names, ex: Winner: Alex Loser: Leo.
My problem is that I don't know how to access the 2 names by index.
I would like something like this:
Row 1: Winner: Alex
Loser: Leo
and I would like to access the row like this: dictionary[x] -> so I can get the row and then once I have the row I want to access it like a=raw[y] and b=raw[y+1]. And then I want to print A and B. I want to do this because I have to copy just one specific player from every single row and to save it into another dictionary.
This is the code that I wrote to create the dictionary and to access it but doesn't work as I want.
dicti= imd4.to_dict('index') // dicti is the dictionary that I created and imd4 is the dataset containing the Winner and the Loser name
for x in dicti:
print (x,':')
for y in dicti[x]:
a=dicti[x][y]
b=dicti[x][y+1] //I can't do this but I would like to do it. So I can save the data base on their index
print (y,':',dicti[x][y])
print('Test :' ,a)
Here you can see how the dataset is build
Thank you in advance for your help.

Let's set up a test dictionary:
test_dictionary=[
{'winner':'ross','loser:'chandler'},
{'winner':'rachael','loser:'phoebe'},
{'winner':'joey','loser:'monica'},
{'winner':'gunther','loser:'chandler'}
]
We can loop through this easily:
for contest in test_dictionary:
print (contest)
and we could add a line number using the enumerate function:
for line_number, contect in test_dictionary:
print (line_number,contest)
so now we have the line number we can easily access the next element - we have to bear in mind though we don't want to access the final element as we can't print the contest after this so we loop to the [-1] element:
for line_number, contect in test_dictionary[:-1]:
print (line_number,contest)
print (line_number+1,test_dictionary[line_number+1])
We could also simply use a range on the length of test_dictionary and access the elements directly:
for line_number in range(len(test_dictionary)-1]:
print (line_number,test_dictionary[line_number])
print (line_number+1,test_dictionary[line_number+1])

Related

a bunch of user inputs (like a recipe), how can I skip to a line?

I'm writing a code as a "checklist" for something that is to be made.
each line is basically:
a0=int(input(f'do step one, then enter 1 to cont')
a1=int(input(f'do step two, then enter 1 to cont')
So, how can I skip to line a4 (or a(n) ) and continue from there?
My thoughts were to define each line and store each variable in a list. Then use a while loop to start from wherever. I just can't figure out how to eh, this is where I lose it. I guess I'm trying to convert the string to a variable name, to define it from there. See below:
ail=len(ai) #where ai=[a0,a1,a2..]
a=0 #i would input a as any val.
while a in range (0,ail):
b=(f'a{a}') #this line would determine the "instruction line" to start from.
exec("%s = %d" % (b,b)) #this is the line that names a var from a string
b0=int(input(f'{b}'))
I suggest you use dictionary instead of list. you can access the elements of dictionary using keys and that is going to help you pick a specific spot to traverse from.
Dictionary keys

Parsing and arranging text in python

I'm having some trouble figuring out the best implementation
I have data in file in this format:
|serial #|machine_name|machine_owner|
If a machine_owner has multiple machines, I'd like the machines displayed in a comma separated list in the field. so that.
|1234|Fred Flinstone|mach1|
|5678|Barney Rubble|mach2|
|1313|Barney Rubble|mach3|
|3838|Barney Rubble|mach4|
|1212|Betty Rubble|mach5|
Looks like this:
|Fred Flinstone|mach1|
|Barney Rubble|mach2,mach3,mach4|
|Betty Rubble|mach5|
Any hints on how to approach this would be appreciated.
You can use dict as temporary container to group by name and then print it in desired format:
import re
s = """|1234|Fred Flinstone|mach1|
|5678|Barney Rubble|mach2|
|1313|Barney Rubble||mach3|
|3838|Barney Rubble||mach4|
|1212|Betty Rubble|mach5|"""
results = {}
for line in s.splitlines():
_, name, mach = re.split(r"\|+", line.strip("|"))
if name in results:
results[name].append(mach)
else:
results[name] = [mach]
for name, mach in results.items():
print(f"|{name}|{','.join(mach)}|")
You need to store all the machines names in a list. And every time you want to append a machine name, you run a function to make sure that the name is not already in the list, so that it will not put it again in the list.
After storing them in an array called data. Iterate over the names. And use this function:
data[i] .append( [ ] )
To add a list after each machine name stored in the i'th place.
Once your done, iterate over the names and find them in in the file, then append the owner.
All of this can be done in 2 steps.

I need to create a dictionary that counts the number of times a name appears in a list

I have this code so far:
def name_counts(name_list):
name_dict = {}
for word in name_list:
if word in name_dict:
name_dict[word] += 1
else:
name_dict[word] = 1
print(name_counts(name_list))
which is resulting in:
but I need it to only print the first names, not the lasts. How would I do that? I know that I should use the split function but anytime I do name_list.split() it returns with an attribute error.
The Counter from the collection module does just that! You can use:
from collections import Counter
# get firstname from name
print(Counter(firstname))
EDIT: I'll let you figure out how to parse the firstname :)
You are very close! What you are doing in your function right now is just looking at the full name, while the directions say you should just be looking at the first name and seeing how much it appeared. what you should have is something like this. While looking through each word in the loop, make an array, lets say name and set it to word.split(). Then like in your following code, check if name[0] (the first name) exists in the list, and increment name_dict[name[0]] if it does. If not, make a new key with name[0] and set it to 1.
I would create a temporary variable at the start of the for loop which would contain the split name, like so:
for word in name_list:
name = word.split()[0]
if name in name_dict:
name_dict[name] += 1
else:
name_dict[name] = 0
Note that the .split() function returns a list, so to get the first name, you have to get the item at index 0.
Hope that helps!
This can be achieved in a single line using list comprehensions.
>>>from collections import Counter
>>>name_list = ["Davy Jones", "Davy Crockett", "George Washington"]
>>>Counter([name.split()[0] for name in name_list])
#result -->
Counter({'Davy': 2, 'George': 1})

Python: Generate List name from file

Hi there I want to add a file to python with a few diffrent list in it like
File.txt:
ListA=1,2,3,4 ListB=2,3,4
I want to save the list in my script with the same name like in the File.txt. For example: ListA=[1,2,3,4] ListB=[2,3,4] After that I want to copy one list to a new list called for example li that I can use it. Here is my Script which dont work that u can see what I mean.
So 1st of all: How can I read lists from a txt file and use their name? 2nd How do I copy a specific list to a new list? Hope someone can help me :) And I hope it have not allready been asked.
def hinzu():
#file=input('text.txt')
f=open('text.txt','r')
**=f.read().split(',')
print ('li',**)
#this give me the output **=['ListA=1','2','3','4'] but actualy I want ListA=['1','2'...]
def liste():
total=1
li=input('which list do you want to use?')
for x in li:
float(x)
total *= x
print('ende', total)
You need to split the text by = sign which will seprate the list name with list contents then split the content by ,
f=open('text.txt','r')
a,b=f.read().split('=')
print (a,list(b.split(','))
Split your input first by =, then by ,:
name, list = f.read().split('=')
list = list.split(',')
You may want to add another .split() for your ListB.
To set the name as a variable in the global name scope you can use:
globals().update({name:list})

Getting a specific value from a CSV file with Python raw_input?

Currently, I have a CSV file set out like this:
Element,Weight
"Hydrogen","1"
"Oxygen","16"
Eventually it'll have all of the elements and their atomic weights next to them, but putting all of that in is rather pointless unless I get this issue solved first.
The main Python program is as follows:
import csv
reader = csv.reader(open("chem.csv", "rb"))
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
if first == "Hydrogen" or "hydrogen":
for Weight in reader:
print Weight
else:
print "No."
Now, as you might be able to tell from that, my aim here is to have the program display the weight of hydrogen as taken from the CSV file, for now. However, currently it just ends up displaying the following:
Enter first element: hydrogen
Enter second element: oxygen
['Element', 'Weight']
['Hydrogen', '1']
['Oxygen', '16']
So, basically, how can I make it so that it goes to the Hydrogen row and then takes the weight value from the second column? I should be able to go from there to nail the rest of the program, but this part has got me stuck.
As a secondary thing, is it at all possible to have it so that I won't have to have what is essentially a list of elements in the main Python program as well as in the CSV file? It'd cut down a lot on the clutter, but I just can't get it figured out.
Instead of iterating over the data it is probably nicer to store it in an easy accessible way, e.g. a dictionary mapping name to weight. Then you can just do a look-up for the entered string and display the result (or not if there is none).
import csv
#Read in data anbd store it in dictionary.
#The element name will be stored in lowercase.
elemen_data = { element.lower():int(weight) for element,weight in csv.reader(open("in", "rb"))}
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
#Look for the weight of the entered element (after converting it to all lowercase)
weight_first = elemen_data.get(first.lower())
weight_second = elemen_data.get(second.lower())
if weight_first is not None:
print 'First Element:', first, 'Weight:', weight_first
else:
print 'First Element', first, 'not found'
if weight_second is not None:
print 'Second Element:', second, 'Weight:', weight_first
else:
print 'Second Element', second, 'not found'
Storing your data apart from you program logic can make sense if you want to be able to easily make changes to the data without touching the program. So having a csv-file that is read in is absolutely okay. (As long as the data has a reasonable size)
The problem is that when you iterate over csv.reader object you receive csv file rows as lists of your row cells values. So you can try next for your case:
if first in ("Hydrogen", "hydrogen"):
for Weight in reader:
if Weight[0] == first:
print Weight[1]
That's not the best code, but that returns the value you wanted.
First problem:
if first == "Hydrogen" or "hydrogen":
That won't return what you want. You either want:
if first == 'Hydrogen' or first == 'hydrogen':
or
if first in ['Hydrogen', 'hydrogen']:
Or better yet:
if first.lower() == 'hydrogen'
Which would work for all capitalizations, like HYDrogen.
Then, in that you can do what you want:
for row in reader:
if row[0].lower() == first.lower():
print row[1]
Of course, this could be cleaned up a bit by using a dictionary of values; you probably don't want an if statement for every element, but there you go.

Categories

Resources