Home > Net >  How to add prefix and suffix to dictionary value which is not None
How to add prefix and suffix to dictionary value which is not None

Time:01-20

I have a dictionary and inside this dictionary have some values as lists. And some values are none. I want to add prefix and suffix for these key values which are valid list items. And keep blank in None values. How can I do this?

dict = {
1: ['Item A1', 'Item A2', 'Item A3'],
2: ['Item B1'],
3: '',
4: ['Item C1', 'Item C2', 'Item C3'],
5: '',
6: ['Item D1', 'Item D2']
}

prfix_p = '<p>'
suffix_p = '</p>'

I want to achieve something like this

<p>Item A1</p>
<p>Item A2</p>
<p>Item A3</p>

CodePudding user response:

"" is not None. it's an empty string. You can do something like:

dict_ = {
    1: ['Item A1', 'Item A2', 'Item A3'],
    2: ['Item B1'],
    3: '',
    4: ['Item C1', 'Item C2', 'Item C3'],
    5: '',
    6: ['Item D1', 'Item D2']
}

prefix_p = '<p>'
suffix_p = '</p>'

for k, v in dict_.items():
    if v:
        dict_[k] = [prefix_p   item   suffix_p for item in v]

Then when you print the dictionary's item :

for k, v in dict_.items():
    print(k, v)

output:

1 ['<p>Item A1</p>', '<p>Item A2</p>', '<p>Item A3</p>']
2 ['<p>Item B1</p>']
3 
4 ['<p>Item C1</p>', '<p>Item C2</p>', '<p>Item C3</p>']
5 
6 ['<p>Item D1</p>', '<p>Item D2</p>']

* Note: do not use built-in names(dict) as you variable names.

CodePudding user response:

Do you want to print the results? If so, it's pretty simple:

for item in d.values():
    if item:
        for value in item:
            print(f"{prfix_p}{value}{suffix_p}")

Output:

<p>Item A1</p>
<p>Item A2</p>
<p>Item A3</p>
<p>Item B1</p>
<p>Item C1</p>
<p>Item C2</p>
<p>Item C3</p>
<p>Item D1</p>
<p>Item D2</p>
  •  Tags:  
  • Related