简体   繁体   中英

Python: printing dictionary of dictionary with variables

I'm trying to retrieve some values from a dictionary, should be fairly easy.

For whatever reason, I cannot use a variable to retrieve a value.

I have two dictionaries, one with a mapping of uids -> usernames (via getent passwd), and a second dictionary which contains a dictionary for each key, basically:

dMap = { 12345678: 'username' }
qDict['12345678'] = {'used': '4204224',  'grace': 'none', 'quota': '5242880'}

Obviously there are many more values for both dictionaries, but the structure I've shown is the basic concept.

They key for qDict would be a uid (which should be mapped via the dMap dictionary)

Where I'm having trouble is the following:

for k,v in dMap.items():
    print 'Key: ',k
    print qDict[k]

When I run the script, I get:

Traceback (most recent call last):
  File "./test.py", line 156, in ?
    main() 
  File "./test.py", line 98, in main
    print qDict[k]
KeyError: 26617862

If I comment out the: print qDict[k] line above, and only print the value of k, the key names are printed without issue. I can also reference the dictionary outside of the for loop with an actual keyname (12345678):

print dMap[26617862]         # this works!
print qDict['26617862']      # this works!      #NOTE BELOW

What I'm trying to do is just have the for loop print the dictionary for the given keyname, kind of printing the dictionary of a dictionary...

What I think the problem is that (if you look at the #NOTE BELOW line) I need to somehow present the dictionary (qDict) with the properly formatted variable.

Is there something I'm missing here, or is there an easier way to do this?

PS: I've also tried the for loop with dMap.keys(), etc.

You built the two dictionaries using different types for the keys. One dict has an integer key and the other has a string key.

As @Mark Byers said, you can convert the integer to a string to do the lookup.

However, I recommend you instead build qDict with integer keys. Wherever your code is that builds qDict , wrap the key in int() to force it to be an integer key.

Either way will work, really. But if dMap has int keys and qDict has str keys, there are some keys possible in qDict that cannot appear in dMap , and if the two are to match, it's better if they just have the same type of key. And int should be slightly more efficient, so if your program scales up large, it's the better choice.

The keys in dMap are integers, but in qDict the keys are strings.

You need to convert your integer k to a string before using it as a key in qDict :

for k in dMap:
    print 'Key: ',k
    print qDict[str(k)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM