Why is dictionary with only keys len zero? - python

I am trying to make dictionary that are made of only keys. I will populate the value latter. I don't want set. I want key and value data structure. I have variable called legends that has len of 4.
print("len = ",len(my_legends)) # prints 4
plot_param=dict()
plot_param.fromkeys(my_legends)
print("dic len = ", len(plot_param)) # prints 0, I was hoping it to be 4.
for key in plot_param:
print("key == ") # cannot print values at all.
I was planning to loop over the keys and populate its values now I cannot loop at all.

Instead of
plot_param.fromkeys(my_legends)
You probably wanted:
plot_param = dict.fromkeys(my_legends)

Related

Update dictionary and create key-value pairs with loop values

i'm trying to append to a dictionary. there are two loops. the name of the keys depends on the value of the inner loop and the key is the value of a variable which is updated within the loop. my script is
def append_value(dict_obj, key, value):
# Check if key exist in dict or not
if key in dict_obj:
# Key exist in dict.
# Check if type of value of key is list or not
if not isinstance(dict_obj[key], list):
# If type is not list then make it list
dict_obj[key] = [dict_obj[key]]
# Append the value in list
dict_obj[key].append(value)
else:
# As key is not in dict,
# so, add key-value pair
dict_obj[key] = value
for x in range(tot):
dict=['output'=x]
for a in range(33,91):
index_val=(a*sum_t)/x
# now i'm trying to create key names that would be year_33 year_34 and so on
head=''
head='year_{}'.format(a)
append_value(dict, head=avg_PMI)
i get the error name 'append_value' is not defined. would appreciate any help. i would like to loop over values of tot and the (33,91) range. each combination of the two gives a unique values and i want to create a dictionary which will become a csv where x values are rows, a is the column.
thanks!
edited: to show append_value function
The cause of the error is that when you call a function with head=avg_PMI, python assumes that head is an argument. For append_value, the only arguments are dict_obj, key and value. I assume that you want to add a value to the dictionary such that head=avg_PMI. To do this, you have to call the function append_value in the following way:
append_value(dict, head, avg_PMI).

Adding to dictionary keys

I'm trying to create a running leaderboard in which each person starts with one point and I add to the key if they accomplish something. I'm not certain a dictionary is the best way to do it so recommendations are definitely welcomed.
I tried a list to begin with but a dictionary seemed to better suit my needs as I had lists inside of lists
myDict = {'person1' : 1 , 'person2' : 1 , 'person3' : 1}
If person1 were to do something i'd like their key to change to 2. I need to increment the keys, not assign a specific key. Also I will continually add entries to the dict for which I need their default value to be 1.
edit: Chris had a super helpful suggestion to use collections.defaultdict so that calling key that isn't in a dict adds it instead of returning a keyerror
A value can be added or changed or reassigned in a python dictionary by simply accessing through it's key
myDict[key] = value
In your case:
myDict["person1"] = 2 # Reassignment or changing
myDict["person1"] += 1 # Increementing
If the key doesn't exist, incrementing will be a problem. In that scenario, you need to check if the key is present or not.
if myDict["person5"]:
myDict["person5"] += 1
else:
myDict["person5"] = 1
Reference https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Unless you want to do something like sorting players by scores at the end, a dictionary seems a good option. (You can do the sorting but have to have a workaround since dictionary is only indexed by its keys)
Otherwise you can do the following to update the scores
myDict = {}
person = '<person_name>'
# in case the person did something
if person in myDict:
myDict[person] += 1
else:
myDict[person] = 1
You can update a dictionary as follows:
>>> myDict = {'person1': 1, 'person2': 1}
>>> myDict['person7'] = 2
You may also want to investigate
import collections
myDict = collections.defaultdict(lambda: 1)
myDict['person7'] += 1
as this will automatically initialize unset values to 1 the first time they are read.

how to subtract a value of a key in python dictionary

I'm learning python and I'm trying to use this function I built and its not working. The function is not changing a single value in the dictionary as it is working now, although it should. I'd like to get some help
def delete_product(diction):
product_to_delete = raw_input()
for key,value in diction.items():
if key == product_to_delete:
value = value - 1
if (value == 0):
del diction[key]
print "removed"
raw_input()
print "we couldnt remove the product because it does not exist"
raw_input()
Mistake in this code snippet:
value = value - 1
if (value == 0):
del diction[key]
Instead of modifying value in the dictionary, you are only modifying local value. So, this function will delete the required entry only when value happens to be 1.
You can modify it as follows or any variation of it:
if value == 1:
del diction[key]
break
else:
diction[key] = value - 1
Moreover, please note that you have to break out of the for loop once the entry is deleted from the dictionary. If you modify the dictionary while you are iterating it, the iterator will not work after that. If you want to delete multiple keys in one iteration, first get list of all keys to be deleted within the loop and delete after the loop.

How to make a list of dicts with nested dicts

I am not sure if thats what i really want but i want this structure basically,
-document
-pattern_key
-start_position
-end_position
right now i have this
dictionary[document] = {"pattern_key":key, "startPos":index_start, "endPos": index_end}
but i want to nest startPos, endPos under pattern key
Also how can i update this, to add a new entry of pattern_key, startPos, endPos, under same document?
with this you can updates values of the keys
for x in dict.keys():
if 'pattern_key' in x:
dict[x]= 'new value'
if 'endPost'...
.....
print dict
>>> should have new values
for add new entrys:
old = {}
old['keyxD'] = [9999]
new = {}
new['newnewnew'] = ['supernewvalue']
new.update(old)
print new
>>>{'newnewnew': ['supernewvalue'], 'keyxD': [9999]}
Not sure what you exactly want, but you can try this:
document = {'pattern_key' : {}}
This created an object document which is a dictionary, where the key is a string (pattern_key) and the value is another dictionary. Now, to add new entries to the value of the dictionary (which is another dictionary) you just add your values:
document['pattern_key']['start_position'] = 1
document['pattern_key']['end_position'] = 10
Afterwards, you can enter either case with document['pattern_key']['start_position'] = 2 and this will change the start position to 2.
Hope this helps

Adding items to dictionary

I am trying to create a dictionary in python. To be more specific I want to read the input from the keyboard and then add it to dictionary. I am new to python and I don't know how can this be achieved.
for i in range(3)
key=input("Give key\n")
name=input("Give name\n")
#add these values in a dictionary
At first create empty dict:
d = {}
and then set values:
for i in range(3)
key=input("Give key\n") # use raw_input in python 2x
name=input("Give name\n")
d[key] = name
You can create a dictionary with
myDict = dict()
Set a value in it by
myDict[myKey] = 'myValue'
Read a value from it with
myDict[myKey] #Result: 'myValue'
Check whether a key exists in a dictionary with
myKey in myDict #Evaluates to a bool
For your problem:
Create a dictionary outside your loop
Add each entered value at the desired index as I showed you above.

Categories