Home > Net >  How would I pull out similar value pairs from a dictionary and put them in a new dictionary? Python
How would I pull out similar value pairs from a dictionary and put them in a new dictionary? Python

Time:12-05

I have a dictionary filled with 3 keys: "Ticker", "Title" and "Value". The ticker key contains 100 stock tickers that corresponds to the value of the purchase and title that are in the same position. So here is an example of the dictionary:

{'Ticker': {0: 'AKUS', 1: 'HHC', 2: 'IOVA', 3: 'DDOG'},
 'Title': {0: '10%', 1: 'Dir, 10%', 2: 'Dir', 3: 'Dir'},
 'Value': {0: ' $374,908,350', 1: ' $109,214,243', 2: ' $65,000,000', 3: ' $49,999,940'}}

So "AKUS" corresponds with the 10% and $374,908,350.

I am only showing 4 items in the dictionary but my actual dictionary has 100.

My question is regarding a new dictionary that only contains tickers and values but everything in that dictionary has the same title.

For example, I want to create a 10% dictionary that contains all the tickers and values of stocks where the title contained 10%.

I know some stocks have multiple titles but I don't mind the same stocks being in more than one dictionary. Would some one be able to let me know how I should go about doing this? Thank you in advance, I have been stuck on this for a while.

CodePudding user response:

Simple to do using pandas if you are OK using that; so assuming your dictionary is named d:

df = pd.DataFrame.from_dict(d)
df10 = df[df['Title'].str.contains('10%')]
print(df10)

produces

  Ticker     Title          Value
0   AKUS       10%   $374,908,350
1    HHC  Dir, 10%   $109,214,243

CodePudding user response:

# Create empty dictionary to hold 10% stocks
ten_percent_stocks = {}

# Iterate over keys and values in original dictionary
for key, value in original_dict.items():
    # Check if title matches "10%"
    if value['Title'] == '10%':
        # Retrieve corresponding ticker and value from original dictionary
        ticker = original_dict['Ticker'].get(key)
        stock_value = original_dict['Value'].get(key)
        
        # Add ticker and value to 10% stocks dictionary
        ten_percent_stocks[ticker] = stock_value

# Print resulting 10% stocks dictionary
print(ten_percent_stocks)

CodePudding user response:

you can create a new dictionary with only the tickers and values that have the same title by looping through the original dictionary and checking the values of the "Title" key. Here's some sample code that should do the trick:

# Create a new dictionary to store the tickers and values with the desired title
new_dict = {"Ticker": [], "Value": []}

# Loop through the original dictionary and check the values of the "Title" key
for i in range(len(original_dict["Ticker"])):
  if original_dict["Title"][i] == "10%":
    # If the title is "10%", add the ticker and value to the new dictionary
    new_dict["Ticker"].append(original_dict["Ticker"][i])
    new_dict["Value"].append(original_dict["Value"][i])

# The new dictionary should now only contain the tickers and values with the desired title
print(new_dict)

Keep in mind that this code assumes that the original dictionary is organized as a dictionary of lists, where each key is a list of values. If your original dictionary is organized differently, you may need to adjust the code accordingly.

CodePudding user response:

As you only want to get the "Ticker" and "Value" values that have a "Title" that contains "10%" in its value, you need to filter both "Ticker" and "Value" against that. You can do it verbose or using dictionary comprehension:

stocks = {'Ticker': {0: 'AKUS', 1: 'HHC', 2: 'IOVA', 3: 'DDOG'},
          'Title': {0: '10%', 1: 'Dir, 10%', 2: 'Dir', 3: 'Dir'},
          'Value': {0: ' $374,908,350', 1: ' $109,214,243', 2: ' $65,000,000', 3: ' $49,999,940'}
         }

ten_percent_stocks = {"Ticker":{}, "Value": {}}

for k, v in stocks["Title"].items():
    if "10%" in v:
        ten_percent_stocks["Ticker"][k] = stocks["Ticker"][k]
        ten_percent_stocks["Value"][k] = stocks["Value"][k]

With dictionary comprehension you could get the same result by doing this:

ten_percent_stocks = {"Ticker": {k: v for k, v in stocks["Ticker"].items() 
                                 if "10%" in stocks["Title"][k]},
                      "Value": {k: v for k, v in stocks["Value"].items()
                                if "10%" in stocks["Title"][k]}
                     }

But I'll find writing the actual for loop a bit cleaner. The result in both cases is:

{'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Value': {0: ' $374,908,350', 1: ' $109,214,243'}}

An additional change in your origin dictionary could be, as you use always the same indices, instead of storing informations in three separate dictionaries, make use of tuples, that stores stocks in the order ticker, title and value, i.e.:

stocks = {0: ('AKUS', '10%', ' $374,908,350'),
          1: ('HHC', 'Dir, 10%', ' $109,214,243'),
          2: ('IOVA', 'Dir', ' $65,000,000'),
          3: ('DDOG', 'Dir', ' $49,999,940')
         }

# Filtering stocks where title contains "10%":
ten_percent_stocks = {k: v for k, v in stocks.items() if "10%" in v[1]}

Giving you the result as follows:

{0: ('AKUS', '10%', ' $374,908,350'), 1: ('HHC', 'Dir, 10%', ' $109,214,243')}
  • Related