English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have created a series of lists in the following format:

acc1 = [value1, value2,...]
acc2 = [value1, value2,...]
acc3 = [value1, value2,...]

these lists are then added to a dictionary with 'value1' as their key:

accounts = {acc1[0]:acc1, acc2[0]:acc2, acc3[0]:acc3,....}

the problem I have is I need the program to be able add new details, ie create a new list called acc4 (5,6 depending on how meny lists there are) and add this new list to the dictionary (in the same format is above)

does anyone have any ideas of the best way to do this?

2007-04-11 23:04:23 · 2 answers · asked by uktshaw 3 in Computers & Internet Programming & Design

The new list name has to be variable not just a simple as acc4 = [ ]

it needs to be generated using something like:

newAccount = "acc" + str(len(accounts)+1)

2007-04-12 00:08:33 · update #1

2 answers

Didn't I help you with a similar issue a few weeks ago? :-)

You can add extra items to a dictionary using this syntax:
dictionary[key] = item

So in your case it would be
accounts[acc4[0]] = acc4

I see from your edit that you want the list to be named dynamically. I'm not sure why though, as the initial name of the list no longer matters once it is in the dictionary. acc3 or acc4 are just temporary names - now you can refer to the new dictionary as accounts[key], where key is whatever you put in value1. There is no longer any reference to the names "acc3" or "acc4".

Think of it like this:

templist = createlist(params)
# createlist is your function that gets values for the list
accounts[templist[0]] = templist

Now you can refer to it via the key.

I must say I wouldn't recommend using list[0] as the dictionary key. Another way of doing it might be via a list of lists:
accounts = []
accounts.append([value1, value2, value3...])
accounts.append([more list values])

now you can refer to accounts[0] which gives you list 1, etc.

If you want to post more details of how you're creating these lists and what you want to do with them, we might be able to help you a bit more.

2007-04-12 01:09:50 · answer #1 · answered by Daniel R 6 · 1 0

Simple:
accounts[acc4[0]] = acc4

Beware: dictionaries in Python have unique keys, therefore if, for example, acc1[0] has the same value as acc2[0] then you will lose the list acc1 from your dictionary, because its first entry, which was acc1[0]:acc1, will be overwritten by acc2.

2007-04-12 06:29:32 · answer #2 · answered by Klint 2 · 0 0

fedest.com, questions and answers