How to add new key-value to dictionary - python

contacts = {'John Smith': '1-123-123-123',
'Jane Smith': '1-102-555-5678',
'John Doe': '1-103-555-9012'}
def add_contact(contacts, name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in contacts:
print(name, "is already in contacts list!")
else:
contacts[name] = number
print(add_contact(contacts, 'new_guy', '1234'))
When I print this I get none
but if I add another line print(contacts)
it will give me a none and the new dictionary with 'new_guy' :'1234'. What is the correct way to print out the new dictionary without printing none?

You're adding to the dictionary correctly. Yor print statement is the issue.
Change this:
print(add_contact(contacts, 'new_guy', '1234'))
You need to separate this out some.
add_contact(contacts, 'new_guy', '1234')
print(contacts)
Also, since your contacts dictionary is declared globally, you don't need to pass it to the function should name it something different in the function for clarity. You could change the function to:
def add_contact(current_contacts, name, number):
But don't for get to change inside the function as well.
if name in current_contacts:
print(name, "is already in contacts list!")
else:
current_contacts[name] = number
The final code:
contacts = {'John Smith': '1-123-123-123',
'Jane Smith': '1-102-555-5678',
'John Doe': '1-103-555-9012'}
def add_contact(current_contacts, name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in current_contacts:
print(name, "is already in contacts list!")
else:
current_contacts[name] = number
add_contact(contacts, 'new_guy', '1234')
print(contacts)

The way you have it right now, you are printing what the function returns (which is none). All you need to do is separate your functional call and print statement like so:
add_contact(contacts, 'new_guy', '1234')
print(contacts)

def add_contact(name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in contacts:
print(name, "is already in contacts list!")
else:
contacts[name] = number
return contacts #put a return statement that will return the updated contacts dictionary
print(add_contact('John Doe', '1234'))
#for simplified version try a dictionary comprehension:
#using the dict.update(), we can use a comprehension inside to iterate from the contacts itself and have a condition if the name is already exists
contacts.update({key: value for key, value in contacts.items() if key not in contacts})
#tho, we can't have a print statement that will tell if the name already exist in the contacts
print(contacts)
>>>output: {'John Smith': '1-123-123-123', 'Jane Smith': '1-102-555-5678', 'John Doe': '1-103-555-9012'}

Related

Creating a dictionary with multiple user input choices in python

I am creating a dictionary in python in which a user enters his information, such as name and role.
Regarding the last two keys, I would like the user to write a simple letter in the input that corresponds exactly to the options I provide.
Example:
`userData= dict()
userData["name"]=input("Insert your name and last name: ")
userData["role"]=input("What is your role? \nA)Professor \nB) Student [A/B]: ")
#print(userData)`
Then below I'd like to create if statements where if the user enters "A" in the role key, it saves the value as "Professor" in the dictionary, and if he/she/them enters "B" it saves the value as "Student".
I tried writing something like this:
if userData["role"]== "A": userData["role"]== "Professor"
Only, in the dictionary, the value that is saved is "A" and not "Professor".
How can I get the value I want by making the user type only one letter?
Thank you in advance
PS: i'm completely new in Python and this is only an exercise class, please be gentle.
Possible solution is the following:
userData= {}
userData["name"]=input("Insert your name and last name: ")
# start infinite loop until correct role will be entered
while True:
role=input("What is your role? \nA) Professor \nB) Student\n").upper()
if role == 'A':
userData["role"] = "Professor"
break
elif role == 'B':
userData["role"] = "Student"
break
else:
print(f"{role} is incorrect role. Please enter correct role A or B")
continue
print(userData)
Prints
Insert your name and last name: Gray
What is your role?
A) Professor
B) Student
B
{'name': 'Gray', 'role': 'Student'}
Another solution that does not require the use of if statements is using another dictionary for role entries.
# define roles dict
roles_dict = {"A": "Professor", "B":"Student"}
# get user data
userData= dict()
userData["name"]=input("Insert your name and last name: ")
role_letter=input("What is your role? \nA) Professor \nB) Student [A/B]: ")
# update dict
userData.update({"role": roles_dict[role_letter]})
print(userData)
Prints:
Insert your name and last name: Jayson
What is your role?
A)Professor
B) Student [A/B]: A
{'name': 'Jayson', 'role': 'Professor'}

How to assign a name to a dictionary based on input from a user

How do we assign a dictionary a name that is taken from input from the user and save that dictionary to a txt file so that we can search for it by its name and print output to the user?
I am currently here:
Any ideas how?
import sys
import pathlib
'''Arg-V's should be in following order <app.py> <action> <nick_name> <name> <phone> <email>'''
if str(sys.argv[1]).lower == 'add':
current = {'Name': sys.argv[3], 'Phone Number': sys.argv[4], 'Email': sys.argv[5]}
with open('contacts.txt', 'w') as f:
f.write(current)
As per Naming Lists Using User Input :
An indirect answer is that, as several other users have told you, you don't want to let the user choose your variable names, you want to be using a dictionary of lists, so that you have all the lists that users have created together in one place.
import json
name = input('name/s of dictionary/ies : ')
names = {}
name = name.split()
print(name)
for i in name:
names[i]={}
print(names)
for i in names:
print(i,'--------->', names[i])
for i in names:
names[i] = '1'*len(i)
for i in names:
with open(i+'.txt', 'w+') as file:
file.write('prova : '+json.dumps(names[i]))

Converting Nonetype into String

I have this code which returns a Nonetype, when I thought it would return a string. And I have been trying to find solutions on stack, but I am yet to find one.
Here is the code:
members = ['Alex', 'Danny', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']
def check_group(members, visitors):
for person in visitors:
if person in members:
print(f"Member present: {person}")
break
else:
print("No members visited")
output: Member present: Danny
You have forgottent a sin when typing members line 2.
Also, your code won't return anythings, just print the value you asked it to print.
You need to have a return statement.
So if this is part of a function then it should be something like this
def find():
members = ['Alex', 'Danny', 'Kieran', 'Zoe', 'Caroline'] visitors = ['Scott', 'Helen', 'Raj', 'Danny']
for person in visitor:
if person in member:
print(f"Member present: {person}")
retrun person
else:
print("No members visited")
return None

I need help on how to save dictionary elements into a csv file

I intend to save a contact list with name and phone number in a .csv file from user input through a dictionary.
The problem is that only the name is saved on the .csv file and the number is omitted.
contacts={}
def phone_book():
running=True
while running:
command=input('A(dd D)elete L)ook up Q)uit: ')
if command=='A' or command=='a':
name=input('Enter new name: ')
print('Enter new number for', name, end=':' )
number=input()
contacts[name]=number
elif command=='D' or command=='d':
name= input('Enter the name to delete: ')
del contacts[name]
elif command=='L' or command=='l':
name= input('Enter name to search: ')
if name in contacts:
print(name, contacts[name])
else:
print("The name is not in the phone book, use A or a to save")
elif command=='Q' or command=='q':
running= False
elif command =='list':
for k,v in contacts.items():
print(k,v)
else:
print(command, 'is not a valid command')
def contact_saver():
import csv
global name
csv_columns=['Name', 'Phone number']
r=[contacts]
with open(r'C:\Users\Rigelsolutions\Documents\numbersaver.csv', 'w') as f:
dict_writer=csv.writer(f)
dict_writer.writerow(csv_columns)
for data in r:
dict_writer.writerow(data)
phone_book()
contact_saver()
as I am reading your code contacts will look like
{
'name1': '1',
'name2': '2'
}
keys are the names and the value is the number.
but when you did r = [contacts] and iterating over r for data in r that will mess up I guess your code since you are passing dictionary value to writerow instead of a list [name, number]
You can do two things here. parse properly the contacts by:
for k, v in contacts.items():
dict_writer.writerow([k, v])
Or properly construct the contacts into a list with dictionaries inside
[{
'name': 'name1',
'number': 1
}]
so you can create DictWriter
fieldnames = ['name', 'number']
writer = csv.DictWriter(f, fieldnames=fieldnames)
...
# then you can insert by
for contact in contacts:
writer.writerow(contact) # which should look like writer.writerow({'name': 'name1', 'number': 1})

How do I return a collection of key:value pairs in python?

Let's say I have a data item person with two properties, name and age, such that;
person
name
age
I want to return this to a caller, but am unsure of what method to use. My ideas so far are however:
A dictionary for each person placed in a list -- Have tried, the syntax to perform were a little tedious, also I got AttributeError
A class with two properties -- I don't even know how to go about this, nor if it even works
My code is looking something like this at the moment:
persons = []
for person in people: # "people" fetched from an API
persons = {
"name": "Foo"
"age": "Bar"
}
return persons
# And then to access returned result
for person in persons:
print(person["name"]) # Gives AttributeError
# DoMoreStuff
First of all - the error you are not returning a list of dicts. Just a single dict. Instead of appending your persons to the list you created, you replace the list with your persons. So if you try to iterate over it, you in fact iterate over the keys. What you wanted is probably:
persons.append({
"name": "Foo"
"age": "Bar"
})
Second of all: to get a "class with two properties" I would recommend looking on namedtuple. https://docs.python.org/3/library/collections.html#collections.namedtuple
zefciu is correct and I would like to expand on his idea. First of all, before dealing with a list of persons, you need to know how to work with a single person. There are three ways to represent a person: a dictionary, a class, and a namedtuple.
Dictionary
Given a person name (John) and age (32), you can represent a person as:
person = {'name': 'John', 'age': 32 } # or
person = dict(name='John', age=32)
You can then access this person's name as person['name'] and age as person['age'].
Class
You can define a person class, along with an initializer as:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Now, you can create and access a person object:
person = Person('John', 32) # or
person = Person(name='John', age=32)
print('Name:', person.name)
print('Age:', person.age)
namedtuple
namedtuple is part of the collections library, so you need to import it. Here is how to define it:
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
To use it:
person = Person('John', 32) # or
person = Person(name='John', age=32)
print('Name:', person.name) # like a class
print('Name:', person[0]) # like a tuple
Populate a List
persons = []
for person in people:
name = ... # extract name from person
age = ... # extract age
persons.append(dict(name=name, age=age)) # For dictionary
persons.append(Person(name=name, age=age)) # For class or namedtuple

Categories

Resources