how to add key and value in dictionary python? - python-3.x

I am trying to add some value and key in python dictionary using following script
print('phone book contacts')
contacts = input('how many contacts to add: ')
i = 0
for i in range(int(contacts)):
phone_book = {}
a = input('name: ')
b = input('number: ')
phone_book[a] = b
print(phone_book)
when i input 2 key & value like these:
adam : 08123
daniel : 0877
I expect the output will be like these:
{'adam':'08123', 'daniel':'0877'}
instead I get the following output:
{'daniel': '1234'}
any ideas how to show dictionary key & value similar with my expected output?

You can try something like this:
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
# Taking input key = 1, value = test
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
dict_obj.add(2, 'test2')
print(dict_obj)

Use update() method of dictionary class in python.
So if applied to your code
It would be
print('phone book contacts')
contacts = input('how many contacts to add: ')
i = 0
phone_book = {}
for i in range(int(contacts)):
a = input('name: ')
b = int(input('number: '))
phone_book.update({a : b})
print(phone_book)
Since number is integer you have to use curly braces.
And yes move phone_book = {} above the loop because it will be set to empty every time it loops.

Related

How can I convert a string that has a lot of white space and contains what would be duplicate keys into a dictionary using Python?

I have a list of strings that I need to convert into a dictionary. The strings within the list contain a lot of whitespace and '\n'. It looks something like:
my_list = ['Jim: 5\n', 'Sue : 182\n', 'Jim: 112.2\n', 'Ron: abx']
I need to convert this to a dictionary with the names as keys, and, if it's a duplicate key, adding the value to the already added key:value pair. And I need to be able to ignore the values that aren't floats/integers. So, I want to come up with something like this:
my_dict = {'Jim': 117.2, 'Sue': 182, 'Ron': 0}
Thanks for any help!
Edit:
The answer below was really helpful. Thanks! I changed the suggested code to this because i need the values to be floats:
my_list = ['Jim: 5\n', 'Sue : 182\n', 'Jim: 112.2\n', 'Ron: abx']
result = {}
for ele in my_list:
(key, val) = ele.split(':')
if key not in result:
key = ''.join(e for e in key if e.isalnum())
val = ''.join(e for e in val if e.isalnum())
try:
float(val)
result[key] = float(val)
except:
result[key] = 0
print(result)
This was the output:
{'Jim': 5.0, 'Sue': 182.0, 'Ron': 0}
However, I don't know how to get the value for the second Jim ('Jim: 112.2\n') to get added to the first Jim key:value pair instead of just being ignored. Any tips?
I need it to return this:
{'Jim': 117.2, 'Sue': 182.0, 'Ron': 0}
my_list = ['Jim: 5\n', 'Sue : 182\n', 'Jim: 112.2\n', 'Ron: abx']
result = {}
for ele in my_list:
(key, val) = ele.split(':')
key = ''.join(e for e in key if e.isalnum())
val = ''.join(e for e in val if e.isalnum())
result[key] = val
print(result)
You can avoid the join but directly utilizing the output from split using indexes
my_list = ['Jim: 5\n', 'Sue : 182\n', 'Jim: 112.2\n', 'Ron: abx']
result = {}
for ele in my_list:
temp = ele.split(':')
#### Extracting the key using index - 0 and striping and whitespaces
key = temp[0].strip()
#### Extracting the value using index - 1 and striping and whitespaces
val = float(temp[1].strip())
#### Key existence , if the key exists , add the existing value to the current value
if key in result:
result[key] += val
else:
result[key] = val
>>> print(result)
{'Jim': 117.2, 'Sue': 182.0}

How to read first N lines of a file and save it in dictionary?

In a file contents are mentioned like this: "a b c", "3"
I want to save it in the dictionary: dic={"a b c":"3"}
I used the following code snippet but I can't get the correct output for all 3 lines.
I also do not want to use the JSON file
def exam():
with open("questions.txt") as myfile:
head = [next(myfile) for x in range(3)]
print(head)
a_dictionary = {}
for line in head:
key, value = line.split(",")
a_dictionary[key] = value
print(a_dictionary)
exam()
If you want to read n lines of a file and create a dictionary of the results then you can do:
def exam(myfile, line_count):
a = dict()
with open(myfile) as myf:
for i in range (line_count):
line_data = myf.readline().strip('\n')
ky, val = line_data.split(',')
a[ky] = val
print (a)
exam('questions.txt', 3)

Read out .csv and hand results to a dictionary

I am learning some coding, and I am stuck with an error I can't explain. Basically I want to read out a .csv file with birth statistics from the US to figure out the most popular name in the time recorded.
My code looks like this:
# 0:Id, 1: Name, 2: Year, 3: Gender, 4: State, 5: Count
names = {} # initialise dict names
maximum = 0 # store for maximum
l = []
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
try:
name = l[1]
if name in names:
names[name] = int(names[name]) + int(l(5))
else:
names[name] = int(l(5))
except:
continue
print(names)
max(names)
def max(values):
for i in values:
if names[i] > maximum:
names[i] = maximum
else:
continue
return(maximum)
print(maximum)
It seems like the dictionary does not take any values at all since the print command does not return anything. Where did I go wrong (incidentally, the filepath is correct, it takes a while to get the result since the .csv is quite big. So my assumption is that I somehow made a mistake writing into the dictionary, but I was staring at the code for a while now and I don't see it!)
A few suggestions to improve your code:
names = {} # initialise dict names
maximum = 0 # store for maximum
with open("Filepath", "r") as file:
for line in file:
l = line.strip().split(",")
names[name] = names.get(name, 0) + l[5]
maximum = [(v,k) for k,v in names]
maximum.sort(reversed=True)
print(maximum[0])
You will want to look into Python dictionaries and learn about get. It helps you accomplish the objective of making your names dictionary in less lines of codes (more Pythonic).
Also, you used def to generate a function but you never called that function. That is why it's not printing.
I propose the shorted code above. Ask if you have questions!
Figured it out.
I think there were a few flow issues: I called a function before defining it... is that an issue or is python okay with that?
Also I think I used max as a name for a variable, but there is a built-in function with the same name, that might cause an issue I guess?! Same with value
This is my final code:
names = {} # initialise dict names
l = []
def maxval(val):
maxname = max(val.items(), key=lambda x : x[1])
return maxname
with open("filepath", "r") as file:
for line in file:
l = line.strip().split(",")
name = l[1]
try:
names[name] = names.get(name, 0) + int(l[5])
except:
continue
#print(str(l))
#print(names)
print(maxval(names))

How to print many variables' names and their values

I have a big chunk of json code. I assign the needed me values to more than +10 variables. Now I want to print all variable_name = value using print how I can accomplish this task
Expected output is followed
variable_name_1 = car
variable_name_2 = house
variable_name_3 = dog
Updated my code example
leagues = open("../forecast/endpoints/leagues.txt", "r")
leagues_json = json.load(leagues)
data_json = leagues_json["api"["leagues"]
for item in data_json:
league_id = item["league_id"]
league_name = item["name"]
coverage_standings = item["coverage"]["standings"]
coverage_fixtures_events =
item["coverage"]["fixtures"]["events"]
coverage_fixtures_lineups =
item["coverage"]["fixtures"]["lineups"]
coverage_fixtures_statistics =
item["coverage"]["fixtures"]["statistics"]
coverage_fixtures_players_statistics = item["coverage"]["fixtures"]["players_statistics"]
coverage_players = item["coverage"]["players"]
coverage_topScorers = item["coverage"]["topScorers"]
coverage_predictions = item["coverage"]["predictions"]
coverage_odds = item["coverage"]["odds"]
print("leagueName:" league_name,
"coverageStandings:" coverage_standings,
"coverage_fixtures_events:"
coverage_fixtures_events,
"coverage_fixtures_lineups:"
coverage_fixtures_lineups,
"coverage_fixtures_statistics:"
coverage_fixtures_statistics,
"covage_fixtes_player_statistics:"
covage_fixres_players_statistics,
"coverage_players:"
coverage_players,
"coverage_topScorers:"
coverage_topScorers,
"coverage_predictions:"
coverage_predictions,
"coverage_odds:"coverage_odds)
Since you have the JSON data loaded as Python objects, you should be able to use regular loops to deal with at least some of this.
It looks like you're adding underscores to indicate nesting levels in the JSON object, so that's what I'll do here:
leagues = open("../forecast/endpoints/leagues.txt", "r")
leagues_json = json.load(leagues)
data_json = leagues_json["api"]["leagues"]
def print_nested_dict(data, *, sep='.', context=''):
"""Print a dict, prefixing all values with their keys,
and joining nested keys with 'separator'.
"""
for key, value in data.items():
if context:
key = context + sep + key
if isinstance(value, dict):
print_nested_dict(value, sep=sep, context=key)
else:
print(key, ': ', value, sep='')
print_nested_dict(data_json, sep='_')
If there is other data in data_json that you do not want to print, the easiest solution might be to add a variable listing the names you want, then add a condition to the loop so it only prints those names.
def print_nested_dict(data, *, separator='.', context=None, only_print_keys=None):
...
for key, value in data.items():
if only_print_keys is not None and key not in only_print_keys:
continue # skip ignored elements
...
That should work fine unless there is a very large amount of data you're not printing.
If you really need to store the values in variables for some other reason, you could assign to global variables if you don't mind polluting the global namespace.
def print_nested_dict(...):
...
else:
name = separator.join(contet)
print(name, ': ', value, sep='')
globals()[name] = value
...

How to add field name in python in arcgis?

I am making one tool, and for this I want to save result of this tool in field that I've added. I want give name to that field on the basis of amenity selection (Here I've given data type of amenity as string. and added a list of values in amenity parameter like Education, Medical, Transportation, etc.). If I select "education" from amenities then my field name is like "Edu_IC". How can I do this? I've added my code snippet below
def setupVulnerability():
GP = ARC.create(9.3)
print(SYS.version)
InputFC = GP.GetParameterAsText(0) # Input Feature Class
print "InputFC:-'%s'" % (InputFC)
Fields = GP.GetParameterAsText(1)
print "Fields:-'%s'" % (Fields)
fieldList = Fields.split(";")
print "fieldList:-'%s'" % (fieldList)
amenity = GP.GetParameterAsText(2)
print "amen:-'%s'" % (amenity)
all_field_names = [f.name for f in arcpy.ListFields(InputFC)]
field_Name = None
try:
for field in fieldList:
field_Name = field[0:3]+ "_" + "IC"
if field_Name in all_field_names:
continue
else :
GP.AddField(InputFC , field_Name , "FLOAT")
field_Name = None
except:
raise ERROR.ScriptError()
if __name__ == '__main__':
setupVulnerability()
I believe the problem is that your "amenity" variable, which receives input from the user, is not referenced when the field is being added.
Something like this should work:
amenity = GP.GetParameterAsText(2)
if amenity == "Education":
field_name = amenity[:3] + "_IC"
GP.AddField(InputFC, field_Name, "FLOAT")

Resources