Reputation: 279
#!/usr/bin/python -tt
# A dictionary Of Each New SSID
WirelessNetwork = {}
WirelessNetwork['name'] = 'baz'
WirelessNetwork['type'] = 'bar'
WirelessNetwork['pass'] = 'foo'
# A list of all SSIDs
networkAddList = (WirelessNetwork)
def addWireless(passedDict={}):
print 'Adding SSID: %s' % passedDict['name']
print 'Of type: %s' % passedDict['type']
print 'With Password: %s' % passedDict['pass']
for networkDict in networkAddList:
addWireless(networkDict)
So I have a List "networkAddList" full of dictionaries ,i.e. "WirelessNetwork". I want to iterate that list "for networkDict in networkAddList" and pass the dictionary itself to my function "addWireless"
When I run the sample code above I get the following error:
TypeError: 'string indices must be integers, not str'
Which makes me think that python thinks passedDict is a string, thus thinking I want string indices i.e. 0 or something rather then the key 'name'. I'm new to python but I am going to have to do this kind of thing a lot so I hope somebody can point me in the right direction as I think its pretty simple. But I can't change the basic idea , i.e. a list of dictionaries.
Upvotes: 0
Views: 2139
Reputation: 106480
Just ran a quick check of the types being referenced, and I'm believing that you were only missing a serial comma (in WirelessNetwork).
So, your code would look something like this:
networkAddList = (WirelessNetwork,)
Your for loop will then properly iterate over the dictionaries.
Upvotes: -1
Reputation: 10857
Actually it's not a list, even with a comma. It's a tuple, which is immutable. I bring this up in case your code is wanting to append anything to this later.
networkAddList = [WirelessNetwork] # or, list(WirelessNetwork)
Upvotes: 0
Reputation: 34974
When debugging in python you can confirm your suspicion that the value being passed is a string with the type function:
print type(passedDict)
When you create your tuple with one element, you need a trailing ",". Also note that a tuple is different from a list in python. The primary difference is that tuples are immutable and lists are not.
#!/usr/bin/python -tt
# A dictionary Of Each New SSID
WirelessNetwork = {}
WirelessNetwork['name'] = 'baz'
WirelessNetwork['type'] = 'bar'
WirelessNetwork['pass'] = 'foo'
# A list of all SSIDs
networkAddList = (WirelessNetwork,)
def addWireless(passedDict={}):
print 'Adding SSID: %s' % passedDict['name']
print 'Of type: %s' % passedDict['type']
print 'With Password: %s' % passedDict['pass']
for networkDict in networkAddList:
addWireless(networkDict)
Upvotes: 2
Reputation: 48330
this is not a list, is the value itself
# A list of all SSIDs
networkAddList = (WirelessNetwork)
with a comma becomes a list
# A list of all SSIDs
networkAddList = (WirelessNetwork,)
Upvotes: 0