Ideally I'd like to do it with a list comprehension. Something like this

result = [(key, value)for key in dict.keys(), value in dict.values()]

but clearly that isn't the right format. Any suggestions?

EDIT:

This seems like what I want to do, but it doesn't work:

result = [(dict.keys[i], dict.values[i]) for i in range(1, len(dict))]

Recommended Answers

Take a look at the final lines of this code snippet:
http://www.daniweb.com/code/snippet216747.html

Jump to Post

All 4 Replies

Take a look at the final lines of this code snippet:
http://www.daniweb.com/code/snippet216747.html

Thanks for that. Weirdly enough, what I'm doing is actually related to counting word frequencies.

I realized that I can just use .items() (feels silly) :)

If you are brave enough to ask questions, then you are not silly!

result = [(key, value)for key in dict.keys(), value in dict.values()]

...

result = [(dict.keys[i], dict.values[i]) for i in range(1, len(dict))]

Just please note that in Python, we use the built-in function dict() to convert certain objects to a dictionary. If you used the above code, you would lose this ability as you're overwriting that built-in function with your list!!

EDIT: Notice how dict is highlighted by the syntax highlighting above like the following built-ins (reserved keywords)

d = {'a':1, 'b':2, 'c':3}
for idx in xrange(15):
    y += my_list[idx]
    if y == 256:
        break
list('123456890')
dict(some_iterable)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.