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
Related
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.
I am trying to make a To-Do list in python.I want to add new tasks in my dictionary and want them to appear when i call them.How can I do that?
dictionary = {} # creating a empty dictionary
while True: # to run the program infinite times
qs = input('->').lower() # command?
if "todo" in qs: # check the command
p = dictionary
print(p)
elif "add" in qs: # command
i = input("what to add?") # what to add in the todo list
dictionary = i
print("Added " + i + " to your To Do list")
else:
print("There was a error!")
The code I tried worked but not as I expected.
It only gave one todo work though I wanted to get all the works I added to the dictionary.
So, what can I try?
You're reassigning the dictionary to an individual item:
dictionary = i
You want to add to the dictionary, presumably like this:
n += 1
dictionary[n] = i
It looks like you're overwriting the dictionary rather than adding a new key/value.
Change
dictionary = i
To
index += 1
dictionary[index] = i
and this should work. You could also use update(), or even a list []
The way you seem to want to use it, you are probably better of using a list
Replace dictionary = {} with dictionary = [] and then replace dictionary = i with dictionary.append(i)
I have a list of dictionaries=
a = [{"ID":1, "VALUE":2},{"ID":2, "VALUE":2},{"ID":3, "VALUE":4},...]
"ID" is a unique identifier for each dictionary. Considering the list is huge, what is the fastest way of checking if a dictionary with a certain "ID" is in the list, and if not append to it? And then update its "VALUE" ("VALUE" will be updated if the dict is already in list, otherwise a certain value will be written)
You'd not use a list. Use a dictionary instead, mapping ids to nested dictionaries:
a = {
1: {'VALUE': 2, 'foo': 'bar'},
42: {'VALUE': 45, 'spam': 'eggs'},
}
Note that you don't need to include the ID key in the nested dictionary; doing so would be redundant.
Now you can simply look up if a key exists:
if someid in a:
a[someid]['VALUE'] = newvalue
I did make the assumption that your ID keys are not necessarily sequential numbers. I also made the assumption you need to store other information besides VALUE; otherwise just a flat dictionary mapping ID to VALUE values would suffice.
A dictionary lets you look up values by key in O(1) time (constant time independent of the size of the dictionary). Lists let you look up elements in constant time too, but only if you know the index.
If you don't and have to scan through the list, you have a O(N) operation, where N is the number of elements. You need to look at each and every dictionary in your list to see if it matches ID, and if ID is not present, that means you have to search from start to finish. A dictionary will still tell you in O(1) time that the key is not there.
If you can, convert to a dictionary as the other answers suggest, but in case you you have reason* to not change the data structure storing your items, here's what you can do:
items = [{"ID":1, "VALUE":2}, {"ID":2, "VALUE":2}, {"ID":3, "VALUE":4}]
def set_value_by_id(id, value):
# Try to find the item, if it exists
for item in items:
if item["ID"] == id:
break
# Make and append the item if it doesn't exist
else: # Here, `else` means "if the loop terminated not via break"
item = {"ID": id}
items.append(id)
# In either case, set the value
item["VALUE"] = value
* Some valid reasons I can think of include preserving the order of items and allowing duplicate items with the same id. For ways to make dictionaries work with those requirements, you might want to take a look at OrderedDict and this answer about duplicate keys.
Convert your list into a dict and then checking for values is much more efficient.
d = dict((item['ID'], item['VALUE']) for item in a)
for new_key, new_value in new_items:
if new_key not in d:
d[new_key] = new_value
Also need to update on key found:
d = dict((item['ID'], item['VALUE']) for item in a)
for new_key, new_value in new_items:
d.setdefault(new_key, 0)
d[new_key] = new_value
Answering the question you asked, without changing the datastructure around, there's no real faster way of looking without a loop and checking every element and doing a dictionary lookup for each one - but you can push the loop down to the Python runtime instead of using Python's for loop.
I haven't tried if it ends up faster though.
a = [{"ID":1, "VALUE":2},{"ID":2, "VALUE":2},{"ID":3, "VALUE":4}]
id = 2
tmp = filter(lambda d: d['ID']==id, a)
# the filter will either return an empty list, or a list of one item.
if not tmp:
tmp = {"ID":id, "VALUE":"default"}
a.append(tmp)
else:
tmp = tmp[0]
# tmp is bound to the found/new 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.
I'm having a bit of a problem, don't even know if this is doable. I have a number of launchers that each have a interface defined with the expected inputs. The input values come as a dictionary. For example:
dict_key = str(req_input[0]['name'])
data = dict(dict_key = value)
Now req_input[0]['name'] is the key I would like to insert into the dictionary. Now I know what I'm doint here only creates a dictionary of the form {'dict_key' : value} but I was wondering if it is possible to create the dicionary as to be the form {'Actual value of dict_key' : value}
Regards,
Bogdan
The best way to do this is simply using the dict literal {}:
data = {dict_key: value}
Other ways would be
data = dict({dict_key: value})
or
data = dict()
data[dict_key] = value
but these are longer so stay with the first one.
Another way is:
data = {}
data[req_input[0]['name']] = value
This way you can add multiple values to the same dictionary, or loop through req_input if you have multiple parameters there, i.e.:
data = {}
for input in req_input:
data[input['name']] = value