-2

I have several dictionaries that I would like to merge into a pd.DataFrame. In order to be able to do that, all the dictionaries need to have a dimension of 1. How can I reduce the dimension of the following dictionary to 1 but so that it remains a dictionary? In cases where there are multiple entries for a dictionary item, it should simply be joined. So myFunds should become '2.0 0.0'

h = {
    'gameStage': 'PreFlop',
    'losses': 0,
    'myFunds': [2.0, '0.0'],
    'myLastBet': 0,
    'peviousRoundCards': ['2S', 'QS'],
    'previousCards': ['2S', 'QS'],
    'previousPot': 0.03,
    'wins': 0
}

To be more precise what my problem is: I want to save all properties of an object in a DataFrame. For that I do vars(Object) which gives me a dictionary, but not all of the entries have the same dimension, so I can't do DataFrame(vars(Object)) because I get an error. That's why I need to first convert vars(Object) into a one dimensional dictionary. But it needs to remain a Dictionary, otherwise I can't convert it into a DataFrame.

Parker
  • 8,539
  • 10
  • 69
  • 98
Nickpick
  • 6,163
  • 16
  • 65
  • 116
  • Your question title is irrelevant to your question content. Do you want to join the list values? – Mazdak Aug 14 '15 at 20:52
  • 1
    relevant questions: [Loop over a dictionary](http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python), [make string from list](http://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings-python) – leo Aug 14 '15 at 20:55
  • Yes I want to join the values. See amended question. – Nickpick Aug 14 '15 at 21:09

1 Answers1

2

You can iterate over the items in the dictionary, and them flatten them with str.join().

We basically tell it to iterate over each key/value pair in the dictionary value, turn it to a string (as you can't concatenate an int and a string), and then put it back in the sictionary

The function func is from here and what it does is makes sure we always have an iterable item

from collections import Iterable

def func(x):
    #use str instead of basestring if Python3
    if isinstance(x, Iterable) and not isinstance(x, basestring):
        return x
    return [x]

for key, val in h.items():
    h[key] = " ".join([str(ele) for ele in func(val)])

Output of h becomes:

{
  'gameStage': 'PreFlop', 
  'losses': '0', 
  'myFunds': '2.0 0.0', 
  'myLastBet': '0',
  'peviousRoundCards': '2S QS', 
  'previousCards': '2S QS',
  'previousPot': '0.03',
  'wins': '0'
}
Community
  • 1
  • 1
Parker
  • 8,539
  • 10
  • 69
  • 98