简体   繁体   中英

How do I unpack tuple which is a dictionary keys to create another dictionary?

I have a dictionary which has tuple as its keys and I have tried to unpack the tuples to create another dictionary but am not getting a satisfactory result.

daily_sales = {('naze', 'umuakali'): 6,('peter', 'umuorie'): 1, 
               ('eze','nekede'): 16}

What I want here is another dictionary like

send_to_manag = {{'village': 'naze', 'market':'umuakali', 'sales': 6},
                {'village': 'peter', 'market':'umuorie', 'sales': 1},...}

for each of the items in the dict

I have tried this

send_to_manag = {}
for village,market,sales in daily_sales.items():
    send_to_manag['village'] = daily_sales[0][0][0]
    send_to_manag['market'] = daily_sales[0][0][1]
    send_to_manag['sales'] = daily_sales[0][1]

It gives

KeyError: 0

Simply with dict / list comprehensions:

res = [{'village': t[0], 'market': t[1], 'sales': s} for t, s in daily_sales.items()]
print(res)

The output:

[{'market': 'umuakali', 'sales': 6, 'village': 'naze'},
 {'market': 'umuorie', 'sales': 1, 'village': 'peter'},
 {'market': 'nekede', 'sales': 16, 'village': 'eze'}]

First, in for two values set - tuple and value. Second you overwrite send_to_mang in the loop. Below you find how your loop may be.

send_to_manag = []
for k,sales in daily_sales.items():
    temp = {}
    temp['village'] = k[0]
    temp['market'] = k[1]
    temp['sales'] = sales
    send_to_manag.append(temp)
print (send_to_manag)

results in

[{'village': 'peter', 'market': 'umuorie', 'sales': 1}, 
 {'village': 'eze', 'market': 'nekede', 'sales': 16}, 
 {'village': 'naze', 'market': 'umuakali', 'sales': 6}]

Tuples can be keys, because they are immutable. However, they still behave as normal tuples - which can be accessed via the index. Ie _tuple[0] for the first index, _tuple[1] for the second.

The third value you want is the dictionary value that is key'ed by the tuple. So you just grab that as a value.

daily_sales = {('naze', 'umuakali'): 6,
               ('peter', 'umuorie'): 1, 
               ('eze','nekede'): 16
               }

send_to_manag = [] # Create a new list (the dict in your example output won't work, because you don't have keys associated with the sub-dicts
for k,v in daily_sales.items(): # Get key and value from each item in daily_sales
    village = k[0] # Get the first item form the key tuple
    market = k[1] # Get the second item form the key tuple
    sales = v # Sales is the value associated with the key tuple
    # Now append it to the new list
    send_to_manag.append({'village': village, 'market':market, 'sales': sales})

print(send_to_manag )

OUTPUT:

[{'village': 'naze', 'market': 'umuakali', 'sales': 6}, 
{'village': 'peter', 'market': 'umuorie', 'sales': 1}, 
{'village': 'eze', 'market': 'nekede', 'sales': 16}]

As I said in a comment, dictionaries can't be used as keys in another dictionary. However you could get a list of the dictionaries similar to what you said you wanted as shown below:

from pprint import pprint

daily_sales = {('naze', 'umuakali'): 6,
               ('peter', 'umuorie'): 1,
               ('eze','nekede'): 16}

send_to_manag = []
for (village, market), sales in daily_sales.items():
    send_to_manag.append({'village': village, 'market': market, 'sales': sales})

pprint(send_to_manag)

Printed result:

[{'market': 'umuakali', 'sales': 6, 'village': 'naze'},
 {'market': 'umuorie', 'sales': 1, 'village': 'peter'},
 {'market': 'nekede', 'sales': 16, 'village': 'eze'}]
send_to_management = [ { 'village': key[ 0 ], 'market': key[ 1 ], 'sales': value } for key, value in daily_sales.items() ]

>>> [{'village': 'naze', 'market': 'umuakali', 'sales': 6}, {'village': 'peter', 'market': 'umuorie', 'sales': 1}, {'village': 'eze', 'market': 'nekede', 'sales': 16}]

I hate to have to say this, but the code you've posted above shows a very poor understanding of how dictionaries work.

for village,market,sales in daily_sales.items():

That said, your code above shows a very poor understanding of how dictionaries work. I don't want to be mean, but there are too many errors just those few lines of code for me to discuss properly.

I highly, highly recommend that you investigate more into how dictionaries work- because they are vital to working with code.

Also, generator expressions (and regex) are your friend. Learn them.

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