queen of hearts
queen of hearts

Reputation: 31

How do you make a value from one dictionary the key for a new dictionary in python?

So say I have a dictionary

dict{int: tuple(int, str)}

and I want to make a new dictionary in the format

dict{str: dict{int: int}}

so here's an example of what I'm trying to get:

d1 = {
    1: (22, 'this is a phrase'),
    2: (333, 'here is a sentence')
}

and through a function I need to be able to manipulate that first dictionary to get me this second one:

d2 = {
    'this is a phrase': {1: 22},
    'here is a sentence': {2: 333},

     }

Really sorry for bad formatting initially and the crazy description of what I was trying to get. I just need a simple description on how to get the values to become the keys of the second dictionary. I hope this is somewhat more clear!

Upvotes: 0

Views: 1712

Answers (3)

codelessbugging
codelessbugging

Reputation: 2909

d2 = {}
# we loop through all key: value pairs in the dict
for k, v in d1.items():
    # we unpack the tuple here
    num, newkey = v
    # we then create a new entry for the newkey if it does not exist
    if newkey not in d2:
        d2[newkey] = {}
    d2[newkey][k] = num

and this yields

{'this is a phrase': {1: 22}, 'here is a sentence': {2: 333}}

Edited to fit the changed requirements in the question.

Upvotes: 1

Joe McMahon
Joe McMahon

Reputation: 3382

Iterate over the keys in d1 to get the values to be disassembled. For each value, iterate over the items in the array value[2], and insert {value[0], value[1]} in d2 under each item. Assigning d1[k1] to a temporary variable may make it easier to read:

d2 = {}
for k1 in d1.keys():
    item = d1[k1]
    for k2 in item[2]:
        if k2 in d2:
          d2[k2].append({item[0]: item[1]})
        else:
          d2[k2] = [{item[0]: item[1]}]

Note that we check if the key is there in d2 before trying to append; otherwise Python attempts to fetch d2[k2] and throws a KeyError when k2 is not there.

Upvotes: 0

Green Cell
Green Cell

Reputation: 4777

Assuming that the order of your data is consistent like in your question, you can do the following:

d1 = {
    1: (22, 'this is a phrase',['apple', 'grape']),
    2: (333, 'here is a sentence',['grape', 'cherry'])
}

d2 = {}

for key, values in d1.items():
    for food in values[-1]:
        if food not in d2:
            d2[food] = {}
        d2[food][values[0]] = [values[1]]

print d2

# Output: {'cherry': {333: ['here is a sentence']}, 'grape': {333: ['here is a sentence'], 22: ['this is a phrase']}, 'apple': {22: ['this is a phrase']}}

Upvotes: 1

Related Questions