簡體   English   中英

如何更改 Python 中的字典格式?

[英]How to change format of a dict in Python?

我有一個字典或列表如下。

dictt ={'X , 5,5,8,7,7,6', 'Y , 2,1,2,3,2', 'Z , 3,3,3,4,4,5,4,5,5,4'}

如何將其轉換為以下格式為列表或字典? 我想查看每個 X/Y/Z 的獨特值。 我不應該使用 pandas 或 numpy。

X 5
X 8
X 7 
X 6
Y 2
Y 1
Y 3
Z 3
Z 4
Z 5

原始數據格式:

['endDate,weight',
 ' 2020-06-12  00:00:00+03:00 , 91.5,91.9,91.9,91.9,92.55,92.55,92.55,92.55,92.1,92.1,93.3,93.3 ',
 ' 2020-06-13  00:00:00+03:00 , 91.6,91.6,92.85,92.85,92.85,92.85,92.3,92.3,92.1,92.1,94.1,94.1 ',
 ' 2020-06-14  00:00:00+03:00 , 91.5,91.5,91.65,91.65,91.5,91.5,92.9,92.9 ',
 ' 2020-06-15  00:00:00+03:00 , 91.85,91.85,91.6,91.6,91.85,91.85,92.55,92.55,92.4,92.4,93.7,93.7,93.35,93.35 ',
 ' 2020-06-16  00:00:00+03:00 , 91.6,91.6,91.3,91.3,92.75,92.75,92.15,92.15,93.15,93.15,92.9,92.9 ',
 ' 2020-06-17  00:00:00+03:00 , 91.05,91.05,91.85,91.85,92.4,92.4,92.4,92.4,94.0,94.0,93.7,93.7,93.05,93.05,93.05,93.05 ',
 ' 2020-06-18  00:00:00+03:00 , 91.55,91.55,91.45,91.45,91.25,91.25,91.65,92.2,91.95 ',
 ' 2020-06-19  00:00:00+03:00 , 91.3,91.6,92.45,92.05,91.8,93.1,92.7,93.5,93.15 ',
 ' 2020-06-20  00:00:00+03:00 , 90.8,90.8,90.6,90.6,90.6,90.6,92.15,92.15,92.05,92.05,91.4,91.4 ']

對於您提供的特定輸入,它是一個集合(不是列表或字典):

dictt ={'X , 5,5,8,7,7,6', 'Y , 2,1,2,3,2', 'Z , 3,3,3,4,4,5,4,5,5,4'}

您可以獲得以下內容的字典:

res={i.split(',')[0].strip() : [int(k.strip()) for k in i.split(',')[1:]] for i in dictt}

這給出了以下內容:

>>> print(res)

{'X': [5, 5, 8, 7, 7, 6], 'Z': [3, 3, 3, 4, 4, 5, 4, 5, 5, 4], 'Y': [2, 1, 2, 3, 2]}

如果您現在想按照您的描述分別打印每個鍵及其值,您可以使用以下操作:

for i in res:
    for k in set(res[i]):
        print(i, k)

X 8
X 5
X 6
X 7
Z 3
Z 4
Z 5
Y 1
Y 2
Y 3

假設您的數據結構是一個字典(不是您提供的那個) - 這是代碼。 (如果不是字典 - 請使用實際數據結構更新問題)

data = {'X': '5,5,8,7,7,6', 'Y': '2,1,2,3,2', 'Z': '3,3,3,4,4,5,4,5,5,4'}
for k, v in data.items():
    temp = set(v.split(','))
    for x in temp:
        print(f'{k} {x}')

output

X 5
X 6
X 7
X 8
Y 2
Y 1
Y 3
Z 5
Z 4
Z 3
new_dict = {}
for i in dictt:
    key, value = i.split(' , ')
    value = (int(num) for num in value.split(','))
    value = set(value)
    new_dict[key] = value

這將返回{'X': {5, 8, 7, 6}, 'Y': {2, 1, 3}, 'Z': {3, 4, 5}}形式的字典。 這可能不是您要查找的確切字典,但問題不是很清楚需要什么,並且字典不能有重復的鍵( {'X': 5, 'X': 8}是不可能的)。

dictt = {"X , 5,5,8,7,7,6", "Y , 2,1,2,3,2", "Z , 3,3,3,4,4,5,4,5,5,4"}

l = [[e.strip() for e in splitted] for splitted in [x.split(",") for x in list(dictt)]]

# Removing duplicates by turning them into set and list again
d = {x[0]: list(set(x[1:])) for x in l}

for k, values in d.items():
    for v in values:
        print(f"{k} {v}")

哪個輸出:

X 6
X 5
X 8
X 7
Y 2
Y 3
Y 1
Z 3
Z 4
Z 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM