On Wed, 22 Jan 2014 00:36:17 -0800, indar kumar wrote:

> So my question is if I am giving multiple inputs(a new device say for
> example) in a loop and creating a database(dictionary) for each new
> devices for example. I want subsequent devices to save their data(values
> only not keys) to the database of each of the already existing devices.
> How can I do that? Any hint?I have been stuck here for 3 days.

Short version: 

in your dict (database), instead of storing the value alone, store a list 
containing each of the values.


Longer version:

Here you have a dict as database:


db = {}

Here you get a key and value, and you add then to the db:

# key is 23, value is "hello"
if 23 in db:
    db[23].append("hello")
else:
    db[23] = ["hello"]


Later, you can see if the key already exists:

if 23 in db:
    print("Key 23 already exists")


Or you can add a second value value to the same key:

if 23 in db:
    db[23].append("goodbye")
else:
    db[23] = ["goodbye"]


which can be written more succinctly as:


db.setdefault(23, []).append("goodbye")


Now you can check whether the key has been seen once or twice:

if len(db[23]) == 1:
    print("key 23 has been seen only once")
else:
    print("key 23 has been seen twice or more times")


Does this answer your question?



-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to