简体   繁体   中英

Python Dict() with Id number

I am new to dict(). I try the example of defaultdict . (Python 2.6)

from collections import defaultdict

s = 'happy sad happy cry crazy mad sad'

d = defaultdict(int)

for k in s.split():
    d[k] += 1

print d.items()

Results:

[('crazy', 1), ('sad', 2), ('mad', 1), ('cry', 1), ('happy', 2)]

I just wonder that. Is there any possible to get ID of each dict? Any suggestion?

Expect result:

[(1, 'crazy', 1), (2, 'sad', 2), (3, 'mad', 1), (4, 'cry', 1), (5, 'happy', 2)]

You can add a count to the results using enumerate() , but note that the order is meaningless as dictionaries have no set order:

[(i,) + item for i, item in enumerate(d.items(), 1)]

Demo:

>>> [(i,) + item for i, item in enumerate(d.items(), 1)]
[(1, 'crazy', 1), (2, 'sad', 2), (3, 'mad', 1), (4, 'cry', 1), (5, 'happy', 2)]

Dictionary order depends instead on the history of insertions and deletions. You cannot count on d.items() to return key-value pairs in a specific order.

The order does remain stable as long as you don't add or remove anything from the dictionary, and d.keys() , d.values() and d.items() will produce lists in the same order; zip(d.keys(), d.values()) produces the same pairs as d.items() does. As such, as long as the dictionary itself isn't changed, you can use the specific order for that specific dictionary value and rely on it not to change.

Dictionaries are unordered by default. You might be able to get an ordered dict here .

Keep in mind that your key is your id in some way. So as far as you don't have an id as int . You can always refer to values by their keys. There is no real point to have an index and a key when you have a dict.

If you want to know the size of the dict, you can always use the function len .

d = dict(a=1, b=2, c=3)

len(d)
>>> l = [('crazy', 1), ('sad', 2), ('mad', 1), ('cry', 1), ('happy', 2)]
>>> [(x, y, z) for x, (y, z) in list(enumerate(l, 1))]
[(1, 'crazy', 1), (2, 'sad', 2), (3, 'mad', 1), (4, 'cry', 1), (5, 'happy', 2)]

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