Home > Net >  How to make values to key
How to make values to key

Time:09-21

My List of dict is below

file = [{'key': 'apple', 'type':'fruit'},
        {'key': 'beans', 'type':'vegetable'},
        {'key': 'beans', 'type':'fruit'}]

Expected out

  • value of key is the new key
  • value of type is new value

{'apple': 'fruit', 'beans':['vegetable','fruit']}

code is below

super_dict = {}
for d in file:
    for l, m in d.items():  
        super_dict.setdefault(l, []).append(m)
super_dict

My out {'key': ['apple', 'beans', 'beans'], 'type': ['fruit', 'vegetable', 'fruit']}

CodePudding user response:

Try:

file = [{'key': 'apple', 'type':'fruit'},
        {'key': 'beans', 'type':'vegetable'},
        {'key': 'beans', 'type':'fruit'}]

super_dict = {}
for d in file:
    k, v = d['key'], d['type']
    if k in super_dict:
        super_dict[k].append(v)
    else:
        super_dict[k] = [v]

print(super_dict)

Out:

{'apple': ['fruit'], 'beans': ['vegetable', 'fruit']}

If you truly want output as mentioned, i.e. 'fruit' as a str:

{'apple': 'fruit', 'beans': ['vegetable', 'fruit']}

A slight change could be done:

super_dict = {}
for d in file:
    k, v = d['key'], d['type']
    if k in super_dict:
        item = super_dict[k]
        if isinstance(item, str):
            super_dict[k] = [item, v]
        else:
            item.append(v)
    else:
        super_dict[k] = v

CodePudding user response:

Instead of iterating over the dict.items take the values

super_dict = {}
for d in file:
    l, m = d['key'], d['type']
    super_dict.setdefault(l, []).append(m)
print(super_dict) # {'apple': ['fruit'], 'beans': ['vegetable', 'fruit']}

CodePudding user response:

Try:

file = [{'key': 'apple', 'type':'fruit'},
        {'key': 'beans', 'type':'vegetable'},
        {'key': 'beans', 'type':'fruit'}]

super_dict = {}
newKey = ''
for d in file:
    for l, m in d.items():
        if l=='key': 
            if m not in super_dict:
                super_dict[m]=[]
                newKey=m
        else:
            super_dict[newKey].append(m)
        
print(super_dict)

Out:

{'apple': ['fruit'], 'beans': ['vegetable', 'fruit']}

You need an ' if ' statement to build your dict. Because when make the second iteration with the ' for loop ' your " l " value change from " key " to " type ".

You also need to create a variable like ' newKey ' to store the key value insde the last iteration to build the new dict.

super_dict = {}
newKey = '' 
for d in file:
    for l, m in d.items():
        if l=='key': 
            if m not in super_dict:
                super_dict[m]=[]
                newKey=m
        else:
            super_dict[newKey].append(m)

Now you get something like:

{'apple': ['fruit'], 'beans': ['vegetable', 'fruit']}
  • Related