简体   繁体   中英

How to convert a python dictionary to an 2D array and pad wherever there is mismatch in length?

I'm trying to put dictionary items into an array. The keys are all integer numbers and each value is a list of different length however. I'd like to convert to an array and padd with zeros. I've got the following which

a = {1:[0, 1], 2:[21], 3:[]}
lmax = 0
for item in a.values():
    lmax = len(item) if len(item) > lmax else lmax
t = np.zeros(len(a), lmax)
for key in a:
    t[ key, :len(a[key]) ] = a[key]

Is there a more pythonic way to do this?

Thank you

You seem to be mixing up keys and values in your code, so I'm not sure how that could work.

One way of doing this is

a = {1:[0, 1], 2:[21], 3:[]}
max_length = max(len(item) for item in a.values())
t = [[0] * (max_length - len(item)) + item for item in a.values()]

Or if you want to ensure that the list is in the 'right' order - ie, the item with the lowest key in the original dictionary appears first - you can alter this to

t = [[0] * (max_length - len(item)) + item for _, item in sorted(a.items())]

对于lmax,

lmax = max(map(len, a.values()))

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