레이블이 dictionary인 게시물을 표시합니다. 모든 게시물 표시
레이블이 dictionary인 게시물을 표시합니다. 모든 게시물 표시

2019년 2월 26일 화요일

Python 3.x 에서 Dictionary 정렬하기

Python 3.x 에서 Dictionary를 value가 큰 순으로 정렬하는 여러가지 방법


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def dict_val(x):
    return x[1]

x = {"python": 2, "blah": 4, "alice": 3}

#일반적인방법
sorted_x1 = sorted(x.items(), key=dict_val, reverse=True)
print('sorted_x1',sorted_x1)

#lambda를 이용하는 방법
sorted_x2 = sorted(x.items(), key=lambda t: t[1], reverse=True)
print('sorted_x2',sorted_x2)

#zip을 이용하는 방법
sorted_x3 = sorted(zip(x.values(), x.keys()), reverse=True)
print('sorted_x3',sorted_x3)

결과:

  • sorted_x1 [('blah', 4), ('alice', 3), ('python', 2)] 
  • sorted_x2 [('blah', 4), ('alice', 3), ('python', 2)] 
  • sorted_x3 [(4, 'blah'), (3, 'alice'), (2, 'python')]


2018년 8월 29일 수요일

python에서 두개의 dictionary를 하나로 합치는 방법

How can I merge two Python dictionaries in a single expression?


For dictionaries x and y, z becomes a merged dictionary with values from y replacing those from x.

In Python 3.5 or greater, :
z = {**x, **y}
w = {'foo': 'bar', 'baz': 'qux', **y}  # merge a dict with literal values

In Python 2, (or 3.4 or lower) write a function:
def merge_two_dicts(x, y):
    z = x.copy()   # start with x's keys and values
    z.update(y)    # modifies z with y's keys and values & returns None
    return z

and
z = merge_two_dicts(x, y)

출처: https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression