Unlock Python’s Hidden Tricks: Comprehensions, Counters, and Quick RPC
Explore essential Python tricks—from dictionary and set comprehensions to using Counter for counting, pretty‑printing JSON, and building a quick XML‑RPC file service—showcasing concise code snippets that illustrate the language’s clean syntax and powerful standard library.
1. Dictionary and Set Comprehensions
Most Python programmers know list comprehensions. A list comprehension provides a concise way to create a list.
>> some_list = [1, 2, 3, 4, 5]
>>> another_list = [x + 1 for x in some_list]
>>> another_list
[2, 3, 4, 5, 6]Since Python 3.1 (and even 2.7) the same syntax can create sets and dictionaries.
# Set Comprehensions
>>> some_list = [1,2,3,4,5,2,5,1,4,8]
>>> even_set = {x for x in some_list if x % 2 == 0}
>>> even_set
{8, 2, 4}
# Dict Comprehensions
>>> d = {x: x % 2 == 0 for x in range(1, 11)}
>>> d
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}Set literals can also be written directly:
>> my_set = {1, 2, 1, 2, 3, 4}
>>> my_set
{1, 2, 3, 4}2. Counting with Counter
The collections module provides a Counter class for easy counting.
>> from collections import Counter
>>> c = Counter('hello world')
>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})
>>> c.most_common(2)
[('l', 3), ('o', 2)]3. Pretty‑Printing JSON
Using the json module with the indent parameter produces readable output.
>> import json
>>> print(json.dumps(data)) # No indentation
>>> print(json.dumps(data, indent=2)) # With indentation4. Quick One‑off Web Service with XML‑RPC
A minimal file‑reading service can be built with SimpleXMLRPCServer.
from SimpleXMLRPCServer import SimpleXMLRPCServer
def file_reader(file_name):
with open(file_name, 'r') as f:
return f.read()
server = SimpleXMLRPCServer(('localhost', 8000))
server.register_introspection_functions()
server.register_function(file_reader)
server.serve_forever()Client side:
import xmlrpclib
proxy = xmlrpclib.ServerProxy('http://localhost:8000/')
proxy.file_reader('/tmp/secret.txt')5. The Vibrant Python Open‑Source Community
All examples use only the Python standard library; many third‑party libraries are also available for a wide range of tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
