开发者

Adding dictionary indexes through a function

I've been trying on how to add a new index in a dictionary using a for loop.

I want to keep adding indexes with a for loop each time I enter the value, the 'index' through a function.

So the dictionary just keep growing.

For example:

My dictionary has it's values as lists, and to add values to that list, I can use dictionary[index].append(value)

In a function:

dicc = {'index':[]}

def addStuff(i = '', v = ''):    
    for i in dicc:
        dicc[i].append(v) #adds values to the开发者_如何学运维 list
    return

but it doesn't occurs me adding indexes

I've been trying, and it seems it just doesn't come to mind, yet. So I would want to know what ways there are to keep dictionary's indexes growing through a function. Maybe and probably it's something easy to do, but right now I'm sort of blocked, and yes I've been trying, ... this is why I came here. Thanks in advance. :)


Firstly, as delnan noticed, you seem to have got a little confused in your addStuff function. I'm guessing you want it to add an item v to the list in the dictionary with key i. However, what your function actually does is add item v to every list in the dictionary regardless of what key it has. The value i you pass to the function is completely ignored because it is immediately overwritten by the loop variable.

Suppose dicc contains {'index': [1, 8], 'someOtherIndex': [4, 11]}. If we were to call addStuff('index', 23), or addStuff('someOtherIndex', 23), or even addStuff('supercalifragilisticexpialidocious', 23), we would end up with dicc containing {'index': [1, 8, 23], 'someOtherIndex': [4, 11, 23]} in all three cases.

I'm not sure why you don't just write your addStuff function like this:

def addStuff(i = '', v = ''):    
    dicc[i].append(v)

I'm guessing that your next problem is that this approach doesn't work if the value of i isn't a key in the dictionary. In that case you'd want the function to automatically create an empty list for that key :

def addStuff(i = '', v = ''):    
    if i not in dicc:
        dicc[i] = []
    dicc[i].append(v)


Use the .iteritems(), .iterkeys, and .itervalues() functions.

for key in dicc.iterkeys():
    print key # A key

for key in dicc.itervalues():
    key.append(5) # appends 5 to the value

for (key, value) in dicc.iteritems():
    pass # I have both the key and the value


dicc = {'a':[1]}

def addStuff(keys, vals):
    for key,val in zip(keys,vals):
        if key not in dicc:
            dicc[key] = [val]
        else:
            dicc[key].append(val) #adds values to the list

addStuff('a', '2')
addStuff(['b', 'a'], ['3', 'blah'])
print dicc
# {'a': [1, '2', 'blah'], 'b': ['3']}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜