1

im trying to add to a dictionary that looks like the following

d = {"feline" : {"lion" : 22,
"tiger" : 88 },
"canine" : {"dog" : 12,
"wolf" : 53,
"coyote" : 77} }

im trying to add 'cat' and 55 to the dictionary under feline but im not sure how to acess this. this is what i attempted

fp = raw_input("enter a feline type")
apa = input("enter an amount")
for keys in d :
    if fp not in d[keys] :
        d['feline'] = {fp : int(apa)}

but when i do this the values such as tiger and lion get deleted and the input is replaced for them. for example if i want to add cat under the 'feline' section, usin the above code i get...

{'feline': {'cat ': 55}, 'canine': {'coyote': 77, 'wolf': 53, 'dog': 12}}

how do i keep lion and tiger in the dictionary without overwriting them using dictionaries

Zach Santiago
  • 381
  • 7
  • 18
  • First, the whole point of using dictionaries is that you shouldn't have to loop over them (`for keys in d:`) to find out whether a value exists or not. Second, if you really _do_ need to loop over the keys and values of a dict, it's usually easier to write `for key, value in d:` than `for key in d: something_with(d[key])`. – abarnert Dec 10 '13 at 01:25
  • how do you check if an item exist then? thats how ive always done it – Zach Santiago Dec 10 '13 at 01:30
  • Use the `in` operator. To check if a key exists in a dictionary, it's just `if key in d`. The same as for sets, and any other collections. But meanwhile, why are you checking for it in the first place? – abarnert Dec 10 '13 at 01:49

1 Answers1

9

Simply use item assignment like this

d['feline']['cat'] = 55

For your case, you might want to do,

d['feline'][fp] = int(apa)

When you say,

d['feline'] = {fp : int(apa)}

You are replacing whatever is already there in d['feline'] with a new dictionary ({fp : int(apa)}), instead you can add new key and corresponding value like I have shown above.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • I think what the OP may have been _trying_ to do is `d['feline'].update({fp: int(apa)}`, he just didn't know about `update`. That would actually work. But I have no idea why you'd _want_ to do that—it makes much more sense to just assign a value to a key (as this answer does) than to create a dict with one key and value just to `update` from it… – abarnert Dec 10 '13 at 01:51
  • @abarnert If I have to add more elements to the dict, I would go with `update`, but for a single key-value, that would be an overkill I think. – thefourtheye Dec 10 '13 at 03:04