简体   繁体   中英

Removing spaces from dictionaries key-value pairs

So this is my code for a program adding dicts together.

from collections import Counter
from itertools import chain

def add_sparse_vectors(lst1,lst2):
    dest = dict(Counter(lst1)+Counter(lst2))
    return dest

This is my current output:

>>> v1 = {0:1, 1:3, 2:1}
>>> v2 = {0:1}
>>> add_sparse_vectors(v1, v2)
{0: 2, 1: 3, 2: 1}

Problem is that my assignment asks for this output specifically:

>>> v1 = {0:1, 1:3, 2:1}
>>> v2 = {0:1}
>>> add_sparse_vectors(v1, v2)
{0:2, 1:3, 2:1}
#Note the lack of spaces between the colon and the value in each pair.

Does anyone have a solution for removing this specific space from the key-value pairs in the output? Any help is appreciated.

If you really want to get rid of the spaces, you don't need to implement a custom dict class, like @zondo suggested. The assignment only requires the representation to have no spaces. If add_sparse_vectors returns a string instead of a dictionary, you don't need to change dict 's behavior.

Although I don't think this is particularly elegant, it does get rid of the spaces.

def add_sparse_vectors(v1, v2):
    combined_dict = dict(Counter(lst1)+Counter(lst2))
    key_val_pairs = [str(k)+":"+str(v) for k,v in combined_dict.items()]
    output = "{" + ", ".join(key_val_pairs) + "}"
    return output

you can write your own print function for dictionaries:

def print_dict(d):
    print('{'+', '.join('{}:{}'.format(k, v) for k, v in d.items())+'}')

This does what your exercise asks for, but actually I think that they should not care about having some whitespaces more or less as long as the task is solved correctly...

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