业余时间:Python字典结构

时间:2017-09-22 16:18:59

标签: python pandas dictionary

我还处于学习编程和Python的开始阶段,但我正在努力学习如何最好地使用字典,或者我是否应该这样做。目前,我想要一张表"表#34;采用以下格式:

   user   attr         loc
   ----   ----         ----
    1     red,green    here
    2     blue         there
    3     yellow       here, there
   ...    ...          ...
    n     black        nowhere

出于我想要做的目的,我希望能够打电话给用户= 1'与' attr'列(或有时' loc')作为[' red',' green']等列表返回。

我的问题是:如果我感兴趣的数据不止一列,那么将它作为数据帧视为从给定行检索信息的唯一(或最佳?)方式?看起来字典将仅限于具有键/值对的两列。

非常感谢。

3 个答案:

答案 0 :(得分:2)

字典元素的内容可以是任何内容。所以如果你想要多个东西嵌入另一个字典。

'''
   user   attr         loc
   ----   ----         ----
    1     red,green    here
    2     blue         there
    3     yellow       here, there
   ...    ...          ...
    n     black        nowhere
'''

d = { 
    1: {'attr':('red','green'), 'loc':'here'},
    2: {'attr':('blue'), 'loc':'there'},

    }

if __name__ == '__main__':
    print d
    print d[1]['loc']
    pass

输出:

{1: {'loc': 'here', 'attr': ('red', 'green')}, 2: {'loc': 'there', 'attr': 'blue'}}
here

答案 1 :(得分:1)

  

我想要一张"表"格式为......

我可以建议大熊猫:

import pandas as pd
d = { 
    1: {'attr':('red','green'), '_loc':'here'},
    2: {'attr':('blue'), '_loc':'there'},
    }

df = pd.DataFrame.from_dict(d, orient='index')
df.index.name = 'user'
print(df)
              attr   _loc
user                     
1     (red, green)   here
2             blue  there

请注意,我将列_loc命名为避免与.loc属性混淆。

为了您的目的,这主要为您提供一个更漂亮的数据结构,我认为这个数据结构也更容易,也更灵活:

print(df.loc[1, 'attr'])  # user 1 attrs
('red', 'green')

print(df.loc[1, '_loc'])  # user 1 attrs
here

print(df.loc[1])  # user 1 all records
attr    (red, green)
_loc            here
Name: 1, dtype: object

答案 2 :(得分:0)

如果我理解你的问题,你可以实现一个嵌套字典。

user[1]['attr']
>>>['red','green']
user[1]['loc']
>>>'here'