1

In python2, if I want to print something like:

print 'enrollment:' + str(len(enrollment))
print 'submissions:' + str(len(submissions))

I need to output the title and the length ; tried to format:

print ('%d:' + str(len('%d'))) %enrollment

which gives me:

"TypeError: %d format: a number is required, not dict"

BTW both "enrollment" and "submissions" are variables storing dictionary

Is there a way to apply a placeholder for both string and the variable name?

Smudge
  • 28
  • 4

2 Answers2

0

I think you are perhaps looking for something like the following:

>>> enrollment = {'a':1,'b':2}
>>> submissions = {'a':1,'b':2,'c':3}
>>> for x in ['enrollment','submissions']:
...     print('%s: '+str(len(eval(x)))) % x
...
enrollment: 2
submissions: 3

Note that here the dictionary for a given iteration x is actually the name of the dictionary as a string, which is evaled to get the dictionary for counting

It should also be noted that using eval is generally frowned upon - if the string passed into this function is valid python code, it will get executed - so if the string passed in comes from e.g. user input, the user could potentially run code you don't want to be run. In a case like this where the strings are hard-coded in your own code, it should be fine though.

Jonathon McMurray
  • 2,881
  • 1
  • 10
  • 22
  • If you are going to use `eval` (which is generally frowned upon), then `print '%s: %d' % (x, len(eval(x)))` might be simpler. – cdarke Jan 11 '18 at 16:11
  • I realise `eval` is frowned upon, but in this context, the input is clearly defined, and I can't see any other way of doing what the OP is asking (or at least what I think they are asking). Good point though – Jonathon McMurray Jan 11 '18 at 16:13
  • Thanks~that's the idea – Smudge Jan 11 '18 at 16:17
0

Generally if you need a name to be associated permanently with an object then you should use a dictionary, not try to back-trace from the object back to a variable name. It requires some design thought, but is worth doing if you really need that association, for example:

coll = {'enrollment' : {'k1':'v1','k2':'v2', 'k3':None},
        'submissions': {...}}

for key, val in coll.items():
    print '%s: %d' % (key, len(val))

This avoids eval, which is generally frowned upon: Why is using 'eval' a bad practice?

cdarke
  • 42,728
  • 8
  • 80
  • 84