Append new values to the same key in a Python dictionary - python

I am inputting:
5
A 3
A 2
A 4
B 13
B 14
And I want to put them in the dictionary like this.
{A: ['3', '2', '4'] , B['13','14']}
But I got this:
{'A': ['3', '2', '4'], 'B': ['1', '3', '14']}
I tried:
N = int(input())
d = dict()
for i in range(N):
first,second = [j for j in input().split()]
if first in d:
d[first].append(second)
else:
d[first] = list(second)
print(d)

You want
d[first] = [second]
not
d[first] = list(second)
list(string) iterates over string and places each individual character as a separate element in the list.
[string] creates a list with the entire string as an element.

Here after the input it checks whether it is already in the dictionary and if it appends the new value and if it isn't already there then it creates a new list in the dictionary.
N = int(input())
d = dict()
for i in range(N):
i = input()
lst = i.split()
if lst[0] in d:
d[lst[0]].append(lst[1])
else:
d[lst[0]] = [lst[1]]
print(d)

Related

How do you read input line of text in python and make an array out of those elements and assign last digit to a variable?

You are given as input lines of a file containing a list and integer which is associated with a variable.
line = 1,2,3,4;5
How do i go about making an array out of the first 4 elements [1,2,3,4] and assigning the last element 5 to variable K?
I wanted to split it and get this:
arr = [1,2,3,4]
k = 5
text = "1,2,3,4;5"
myList = text.split(";")
k = int(myList[-1])
myList.pop()
arr = myList
n = len(arr)
i = 0
while(i<n):
left = i
right = min(i + k - 1, n - 1)
while (left < right):
arr[left], arr[right] = arr[right], arr[left]
left+= 1;
right-=1
i+= k
for i in range(0, n):
print(arr[i], end ="")
Thank you everyone. I just needed to split the input and change the type from string to integer.
Here's a one line version using the re module:
import re
line = '1,2,3,4;5'
*arr, k = re.split('[,;]', line)
This gives:
print(arr, k)
['1', '2', '3', '4'] 5
If you need the array (Python list) to be integers instead of strings, you can use:
arr = [int(s) for s in arr]
Hi looking at the input you gave 1,2,3,4;5
If this is the input then:
(a,k) = input().split (";") #this will sperate 1,2,3,4 to arr and 5 to k
arr = a.split(",") #it sperate 1234 and makes a list
print(arr,r)
Please tell me if it works
Here is what you can try:
x='1,2,3,4;5'.split(",")
last=int(x[-1].split(";")[1])
x[-1]=x[-1].split(';')[0]
print(x,last)
OR
x='1,2,3,4;5'.split(';')
print(list(x[0].split(',')),int(x[1]))
You could do something like this:
>>> line = '1,2,3,4;5'
>>> arr, k = line.split(';')
>>> arr = arr.split(',')
>>> arr
['1', '2', '3', '4']
>>> k
5
line.split(';') will split the value separated by ; into two lists.
arr.split(',') will then split all the value separated by ,.

How to append lines in open file before empty line to a dictionary, and then continue appending the following lines until the next empty line?

Coding beginner, thanks in advance!
I have a text file like:
A
B
1
2
C
D
1
2
3
4
E
F
1
2
3
4
5
6
What I'm trying to do is generate a dictionary that turns each section before the empty line into a key and value pair. For example, my dictionary for the text file should be:
{('A','B'): [[1],[2]], ('C','D'):[[1, 3], [2, 4]], ('E','F'):[[1, 3, 5],[2, 4, 6]]}
Right now, I started off my function like this:
while line != '':
# rest of function to append to dictionary here
But I've realized that this only works until the first empty line. If I try to continue reading and print the lines after the function, because of the nature of the while loop, the first line printed is D instead of C. How can I fix this WITHOUT importing anything?
Here is one way you can do it (assuming the file structure is exactly as you said):
First create a string containing all lines:
lines = ''.join(list(open("test.txt")))
#'A\nB\n1\n2\n\nC\nD\n1\n2\n3\n4\n\nE\nF\n1\n2\n3\n4\n5\n6'
Then split into pairs:
pairs = lines.split('\n\n')
#['A\nB\n1\n2', 'C\nD\n1\n2\n3\n4', 'E\nF\n1\n2\n3\n4\n5\n6']
Finally within each pair split key and value:
pairs = lines.split('\n\n')
result = {}
for pair in pairs:
data = pair.split('\n')
key = (data[0], data[1])
first_value = data[2::2]
second_value = data[3::2]
result[key] = [first_value, second_value]
result
Output:
{('A', 'B'): [['1'], ['2']],
('C', 'D'): [['1', '3'], ['2', '4']],
('E', 'F'): [['1', '3', '5'], ['2', '4', '6']]}
Note: data[2::2] means array slicing start from position 2 and iterate every 2 elements
Do this:
txt = x.read_text() # read file as string here
txt = txt.split('\n\n')
txt = list(map(lambda y: y.split('\n'), txt))
keys = list(map(lambda y: y[:2], txt))
values = list(map(lambda y: y[2:], txt))
d = {tuple(key): [[value[0::2]], [value[1::2]]] for key in keys for value in values}

Python 3.6 "IndexError: list index out of range"

Can someone tell me my mistake?
realpair = input("")
realpairfinal = []
rp = list(realpair)
print(rp[0],rp[1])
for i in range(0, len(realpair)):
a = []
v1 = rp[0]
v2 = rp[1]
rp.pop(0)
rp.pop(0)
a.append(v1)
a.append(v2)
realpairfinal.append(a)
pair = realpairfinal
pair2 = realpairfinal
print(realpairfinal)
if my input is 123456, realpairfinal is supposed to be [[1, 2][3, 4][5, 6]] but it tells me:
1 2
Traceback (most recent call last):
v1 = rp[0]
IndexError: list index out of range
realpair = input("")
realpairfinal = []
rp = list(realpair)
for i in range(0, len(realpair)-3):
a = []
v1 = rp[0]
v2 = rp[1]
rp.pop(0)
rp.pop(0)
a.append(v1)
a.append(v2)
realpairfinal.append(a)
pair = realpairfinal
pair2 = realpairfinal
print(realpairfinal)
Subtract three from the length. Output: [['1', '2'], ['3', '4'], ['5', '6']]
pairs = [list(realpair[i:i+2]) for i in range(0, len(realpair), 2)]
This is using a list comprehension to construct a list instead of making an empty list and then appending elements to it.
I'm taking substring of length 2, making it into a list of characters using list() which is then added to the outer list (using list comprehension)

python numpy parse array to get items

Hi I tried taking distinct items of every sublist and making an array
My input is a 2D list
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
And output I want is an array of distinct items
out = [1,2,3,5,15,657]
I tried
from numpy import np
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
anarray = np.array(alist)
newarray = []
for i in anarray:
for j in i:
if j in newarray:
pass
else:
print j
You could make use of a set:
out = set()
for inner in alist:
out.update(inner)
out = map(int, out) # in your example you have a list of ints
>>> print out
[1, 2, 3, 5, 15, 657]
from itertools import chain
alist = [['1', '2'], ['3', '5', '2'], ['15', '1'], ['5', '657', '3', '1']]
# Flatten the list into a single-level list of all the values
flattened_list = list(chain.from_iterable(alist))
# Use a set to remove the duplicates
uniques = set(flattened_list)
# Sort the unique values by the numeric value of each value
sorted_results = sorted(uniques, key=lambda value: int(value))
print sorted_results
Modifying your code slightly you can store your result in newarray:
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
newarray = []
for i in alist:
for j in i:
if j in newarray:
pass
else:
newarray.append(j)
Your result will be stored in newarray
To make it slightly better:
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
newarray = []
for i in alist:
for j in i:
if j not in newarray:
newarray.append(j)

How to read lines from a file in python and remove the newline character from it?

The code for counting the number of inversions in mergesort:
count =0
def merge(left,right):
"""Assumes left and right are sorted lists.
Returns a new sorted list containing the same elements
as (left + right) would contain."""
result = []
global count
i,j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i = i + 1
else:
result.append(right[j])
j = j + 1
count+=len(left[i:])
while (i < len(left)):
result.append(left[i])
i = i + 1
while (j < len(right)):
result.append(right[j])
j = j + 1
return result
def mergesort(L):
"""Returns a new sorted list with the same elements as L"""
if len(L) < 2:
return L[:]
else:
middle = len(L) / 2
left = mergesort(L[:middle])
right = mergesort(L[middle:])
together = merge(left,right)
return together
a=[]
inFile=open('a1.txt','r')
for line in inFile:
fields=line.strip()
a.extend(fields)
print mergesort(a)
print count
where a1.txt contains:
46
45
44
43
42
the list displayed for the integers in the file should be:
[42, 43, 44, 45, 46]
but the output is coming as
['2', '3', '4', '4', '4', '4', '4', '4', '5', '6']
Why so the numbers tens and ones places of the numbers is separated ?
You are doing two things wrong:
You are not converting text to integers
You are using .extend() to add to the list.
The two mistakes conspire to make your code fail.
Use:
for line in inFile:
a.append(int(line))
instead.
Python strings are sequences too. Using a.extend() adds every element of the input sequence to the list; for strings that means individual characters:
>>> a = []
>>> a.extend('foo')
>>> a
['f', 'o', 'o']
list.append() on the other hand, adds individual values to a list:
>>> a = []
>>> a.append('foo')
>>> a
['foo']
int() isn't too picky about whitespace, so even though your line values include a newline, int(line) will work:
>>> int('46\n')
46
You use list.extend, extend accept an iterable and iterate it, it iterates the string letter by letter.
>>> a = []
>>> a.extend('123')
>>> a
['1', '2', '3']
>>>
I think what you want is list.append.
append adds an element to a list, extend concatenates the first list with another list
use a.append(fields) and it will work fine.
with open('a1.txt') as f:
a = list(int(i) for i in f if i.strip())
print(a)
The last if i.strip() is there to skip blank lines.

Categories

Resources