print("\n".join("%s: %s" % (key, value) for key, value in mydict.items()))
? If so, is it hard to do in Java? print("\n".join("%s: %s" % (key, value) for key, value in mydict.items()))
? If so, is it hard to do in Java?Okay, I couldn't resist looking up the old docs, so this looks about right (Enumeration instead of Iterator -- two interfaces that do basically the same thing):
void printTable(Hashtable table)
{
Enumeration e = table.keys();
while(e.hasMoreElements()) {
String key = (String)e.nextElement();
String value = (String)table.get(key);
System.out.println(key + ": " + value);
}
}The best way I can discribe it is like singing. You can have trouble speaking the words to something that you can sing without difficulty.
for(Map.Entry<K, V> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}The temporary list of temporary strings probably will use less memory than the original dict did, though, so it's only a very mild sort of "explosion". It will, however, be several times bigger than the final output string, which also has to be huge if the dictionary is huge.
Python doesn't have anything like a StringBuffer. If it did, it would be reasonable for string_join to use it instead of generating a temporary list. The Python code above would look the same.
But hey, if you just want to print the values, you could say
sys.stdout.printlines("%s: %s\n" % (k, v) for k, v in mydict.items())
but frankly I think I would write instead for k, v in mydict.items():
print "%r: %r" % (k, v)you may have an excellent point, there. But I haven't looked at how cStringIO is implemented: does it construct a list of strings and then join them when they are requested, thus keeping alive all the string objects passed to it? Or does it concatenate the bytes into a buffer?
I just realized that the Python 3 memoryview object also provides the wherewithal to construct a string buffer, even in pure Python.