I am very new to python and am really struggling to find a solution to this issue.
I just don't understand why I need to include only integers in my list when I though they are supposed to support multiple data types.
I've got a very simple field entry system for an account registration and I just can't add the items into a list.
Any help would be greatly appreciated. I've have included my code and the message I receive.
useraccounts = {}
group = []
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
group.append(user accounts)
This is the error message:
Traceback (most recent call last):
File "/Users/admin/Documents/Homework/Computing/testing/testing.py", line 11, in <module>
group['forename'] = forename
TypeError: list indices must be integers, not str
It looks like you want group to be a dict, and useraccounts to be a list. You have them backwards, as well as the append:
useraccounts = [] # <-- list
group = {} # <-- dict
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group) # <-- reversed. this will append group to useraccounts
As written, you were trying to append useraccuonts, an empty list, to group, a dict which has no append method
What you want is a dictionary:
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
In your original code useraccounts stays an empty dict that you just append to the list. If you wanted to add group to useraccounts:
useraccounts['key'] = group
group is a list, it cannot take string indices. It looks like you wanted to use a dictionary instead:
useraccounts = []
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group)
Note that you probably wanted useraccounts to be the list here; your code tried to call .append() on the group object..
or inline the keys and values directly into the dictionary definition:
useraccounts.append({
'forename': forename,
'surname': surname,
'dob']: DOB,
'class': stu_class})
Related
Well, this is my JSON string:
[{"id":1,"name":"firstname lastname","longitude":"45.567856","latitude":"345.2334"},
{"id":2,"name":"firstname1 lastname1","longitude":"45.567856","latitude":"345.2334"}]
This is my code where I'd like to split it:
api = 'http://localhost:8080/serviceBackend/employees'
json_data = requests.get(api).json()
print(json_data)
employeeName = json_data['']['name']
print(employeeName)
If I run this code I'm getting this error TypeError: list indices must be integers or slices, not str
The result should be
firstname lastname, firstname1 lastname1
You can try This:
api = 'http://localhost:8080/serviceBackend/employees'
json_data = requests.get(api).json()
print(json_data)
employeeName = ', '.join([data.get('name') for data in json_data])
print(employeeName)
try this
>>> a = [{"id":1,"name":"firstname lastname","longitude":"45.567856","latitude":"345.2334"},
... {"id":2,"name":"firstname1 lastname1","longitude":"45.567856","latitude":"345.2334"}]
>>> ', '.join([i.get('name') for i in a])
'firstname lastname, firstname1 lastname1'
>>>
you're trying to get variables from loop statement.
you can move by loop with such code:
names = []
for item in json_data:
# get name key from item in type of dictionary and put it in names list
names.apend(item.get('name'))
or using list comprehension, a bit sophisticated but more 'elegant':
names = [item.get('name') for item in json_data]
print(names)
So your code looks like this:
api = 'http://localhost:8080/serviceBackend/employees'
json_data = requests.get(api).json()
print(json_data)
employeeName = [item.get('name') for item in json_data]
print(employeeName)
Table
I am trying to make a dictionary using the values in the table above. I am trying to use 'Genre' as the Key and then a list of tuples for the name, publisher, and platform. variable explorer
D1[genre] = { genre: [(name, publisher, platform),..],..}
My Code:
import csv
fp = open('video_game_sales_tiny.csv','r')
fp.readline()
data_reader = csv.reader(fp)
D1 = {}
for line in data_reader:
name = line[0].lower()
platform = line[1]
year = line[2]
genre = line[3].lower()
publisher = line[4].lower()
D1[genre] = [name, publisher, platform, year]
There are multiple Genres with the same name, and when the loop gets to a genre that matches the Key, it copies over dictionary instead of adding a tuple to the dictionary.
I am trying to make the dictionary look like:
D1 = { Puzzle: [ (Pac-man, Atari, 2600, 1982),(BurgerTime, Mattel Interactive, 2600, 1981), (Q*bert, Parker Bros, 2600, 1982), Shooter: [ (),(), ()], Action: [ (),(), ()] }
You need to make the values of your dictionary an array of tuples. Then you can append new tuples instead of overwriting them. Here is an example using your code:
for line in data_reader:
name = line[0].lower()
platform = line[1]
year = line[2]
genre = line[3].lower()
publisher = line[4].lower()
if genre in D1:
D1[genre].append((name, publisher, platform, year))
else:
D1[genre] = [(name, publisher, platform, year)]
for line in data_reader:
name = line[0].lower()
platform = line[1]
year = line[2]
genre = line[3].lower()
publisher = line[4].lower()
if genre in D1:
D1[genre].append((name, publisher, platform, year))
else:
D1[genre] = [(name, publisher, platform, year)]
I am really stuck with this. I have to create two functions. The first one takes a string as an argument then creates and returns a tuple. The string has the following format: fisrt_name, last_name, salary. However, I must change the order to salary, first_name, last_name. Any ideas on how to do it? This is what I have so far:
def function_one(person_string):
first_name, last_name, salary=person_string.split('')
return salary, first_name, last_name
def function_two(person_tuple):
string_person = ' '.join(person_tuple)
return string_person
path_to_file = 'person.txt'
with open(path_to_file, 'r') as file
content = file.read()
print(content)
with open(path_to_file, 'r') as file:
for line in file.readlines():
tuple_person = string_to_tuple(line)
print(tuple_person)
You can try it like this
def function_one(person_string):
data = person_string.split(' ')
return (data[2], data[0], data[1])
def function_two(person_tuple):
string_person = ' '.join(person_tuple)
return string_person
Jhon = 'Jhon Smith 100000'
string = function_one(Jhon)
out = function_two(string)
print(string, out)
out:('100000', 'Jhon', 'Smith') 100000 Jhon Smith
You could just do something like this?
peoples = ["jordan lee 21", "megan bob 35",]
peoples_2 = []
for people in peoples:
first_name, last_name, salary = people.split()
peoples_2.append('{} {} {}'.format(salary, first_name, last_name))
print(peoples_2)
And if you really need it to be a tuple or list just cast it
tuple(peoples_2)
Just replace the hardcoded peoples list with the previous way you were getting the list.
I have a requirement where in I need to convert my text files into csv and am using python for doing it. My text file looks like this ,
Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football
I want my CSV file to have the column names as Employee Name, Employee Number , Age and Hobbies and when a particular value is not present it should have a value of NA in that particular place. Any simple solutions to do this? Thanks in advance
You can do something like this:
records = """Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football"""
for record in records.split('Employee Name'):
fields = record.split('\n')
name = 'NA'
number = 'NA'
age = 'NA'
hobbies = 'NA'
for field in fields:
field_name, field_value = field.split(':')
if field_name == "": # This is employee name, since we split on it
name = field_value
if field_name == "Employee Number":
number = field_value
if field_name == "Age":
age = field_value
if field_name == "Hobbies":
hobbies = field_value
Of course, this method assumes that there is (at least) Employee Name field in every record.
Maybe this helps you get started? It's just the static output of the first employee data. You would now need to wrap this into some sort of iteration over the file. There is very very likely a more elegant solution, but this is how you would do it without a single import statement ;)
with open('test.txt', 'r') as f:
content = f.readlines()
output_line = "".join([line.split(':')[1].replace('\n',';').strip() for line in content[0:4]])
print(output_line)
I followed very simple steps for this and may not be optimal but solves the problem. Important case here I can see is there can be multiple keys ("Employee Name" etc) in single file.
Steps
Read txt file to list of lines.
convert list to dict(logic can be more improved or complex lambdas can be added here)
Simply use pandas to convert dict to csv
Below is the code,
import pandas
etxt_file = r"test.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if txt_dict.has_key(k):
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
print pandas.DataFrame.from_dict(txt_dict, orient="index")
Output:
0 1
Employee Number 12345 123456
Age 45 None
Employee Name XXXXX xxx
Hobbies Tennis Football
I hope this helps.
How do I look up the 'id' associated with the a person's 'name' when the 2 are in a dictionary?
user = 'PersonA'
id = ? #How do I retrieve the 'id' from the user_stream json variable?
json, stored in a variable named "user_stream"
[
{
'name': 'PersonA',
'id': '135963'
},
{
'name': 'PersonB',
'id': '152265'
},
]
You'll have to decode the JSON structure and loop through all the dictionaries until you find a match:
for person in json.loads(user_stream):
if person['name'] == user:
id = person['id']
break
else:
# The else branch is only ever reached if no match was found
raise ValueError('No such person')
If you need to make multiple lookups, you probably want to transform this structure to a dict to ease lookups:
name_to_id = {p['name']: p['id'] for p in json.loads(user_stream)}
then look up the id directly:
id = name_to_id.get(name) # if name is not found, id will be None
The above example assumes that names are unique, if they are not, use:
from collections import defaultdict
name_to_id = defaultdict(list)
for person in json.loads(user_stream):
name_to_id[person['name']).append(person['id'])
# lookup
ids = name_to_id.get(name, []) # list of ids, defaults to empty
This is as always a trade-off, you trade memory for speed.
Martijn Pieters's solution is correct, but if you intend to make many such look-ups it's better to load the json and iterate over it just once, and not for every look-up.
name_id = {}
for person in json.loads(user_stream):
name = person['name']
id = person['id']
name_id[name] = id
user = 'PersonA'
print name_id[user]
persons = json.loads(...)
results = filter(lambda p:p['name'] == 'avi',persons)
if results:
id = results[0]["id"]
results can be more than 1 of course..