Andrew English
Andrew English

Reputation: 71

how to remove brackets from an inserted tuple in a list?

please can somebody help me remove the extra brackets from my tuple list?

latest_Value = {"17:00:00": 100.00}

Dict1 = {"current value": 100, "stock_purchased": "false", "Historic value": [('16:00:00', 55.50), ("15:00:00", 45.50), ("14:00:00", 75.50),("13:00:00", 65.50), ("12:00:00", 55.50)]}

# converting the latest_value into a tuple
List_it = [(k, v) for k, v in latest_Value.items()]

# insert the tuple into the tuple list
Dict1['Historic value'].insert(0, List_it)

data2 = Dict1["Historic value"]
print(data2)

#output 

[[('17:00:00', 100.0)], ('16:00:00', 55.5), ('15:00:00', 45.5), ('14:00:00', 75.5), ('13:00:00', 65.5), ('12:00:00', 55.5)]

when the list is ammended, it adds a nested list instead of just the tuple. How do you avoid this?

Kind Regards,

Andrew

Upvotes: 0

Views: 556

Answers (1)

DeepSpace
DeepSpace

Reputation: 81594

# converting the latest_value into a tuple
List_it = [(k, v) for k, v in latest_Value.items()]

That is, in fact, wrong. This converts the entire dict to tuples, not just the last key-value pair so Dict1['Historic value'].insert(0, List_it) adds the entire list of tuples to Dict1['Historic value'].

The fact that latest_Value contains a single key-value pair does not change the fact that List_it will be a list of tuples.

If you change to Dict1['Historic value'].insert(0, List_it[0]) then you will get the output you want.

Upvotes: 2

Related Questions